Is it possible to declare variables in state?

Here's how I would do a while loop:

boolean more = true; while (more) { // do something if (someTest()) { more = false; } } 

This is pretty standard. I am curious to know if there is a way to do something similar to the code below in Java: (I think I saw something like this in C)

 // The code below doesn't compile (obviously) while (boolean more = true) { // do something if (someTest()) { more = false; } } 

I only ask about it because at the moment I don’t like how I define the variable used in the condition (in this case: β€œmore”) outside the scope of the loop, although it only matters inside the loop, There is no point in it remained hanging after the cycle ended.


* * Update * *

An idea came to me after visiting the secret secret of Porcaline:

 for (boolean more=true; more; more=someTest()) { // do something } 

This is not perfect; It abuses the for loop, and I cannot think of a way to execute the loop at least once, but it is close ... Is there a way to make sure that the loop runs 1 time?

+6
source share
3 answers

To answer your question literally, you can do

 for(boolean more = true; more; ) { more = !someTest(); } 

but it’s almost the same as

 while(!someTest()); 

If he must complete at least once, when you can do

 do { } while(!someTest()); 
+9
source

In your specific case, you can reduce your code:

 while (true) { if (someTest()) { break; } } 

In general, you can replace the declaration of the outer scope with the inner scope, but you will need to move the loop condition:

 while (true) { boolean more=true; ... if (someTest()) { more = false; } ... if (!more) { break; } } 

Or even:

 do { boolean more=true; ... if (someTest()) { more = false; } ... if (!more) { break; } } while (true); 

I would suggest that defining your state outside the loop is clearer.

+1
source

KidTempo, in the example you gave, I think that more will be reinitialized every time through the loop. Each time passing through the loop, the condition is reevaluated, therefore, assuming that you can define the variable in the conditional expression, the variable will be reinitialized each time this condition is reevaluated. This also applies to other types of conditional expressions, so I would say to avoid defining variables in a conditional expression.

0
source

Source: https://habr.com/ru/post/921974/


All Articles