I have confuse of execution the next code :
label:
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) continue;
if (i == 99) {
continue label;
}
System.out.println("i = " + i);
}
I was hope that this cycle is infinite. But no. When value is 99 - programm was exit. I try to play with continue and break operators but still haven't expected result.
I just try understand why this cycle is not infinite and what i gonna do to make it?
Output :
i = 1
i = 3
......
i = 93
i = 95
i = 97
Process finished with exit code 0
continue continues the labelled loop, which does not involve resetting i to its initial value; so nothing you're doing prevents i from increasing, until it reaches 100 and the loop terminates. And yes, you're correct that the label is unnecessary.
To make it infinite, just reset i within the loop, no need for a label or continue:
for (int i = 0; i < 100; i++) {
if (i == 99) {
i = 0;
}
System.out.println("i = " + i);
}
or perhaps this, which outputs 99 then 0 again and keeps going:
for (int i = 0; i < 100; i++) {
System.out.println("i = " + i);
if (i == 99) {
i = -1;
}
}
Or if for some reason you really, really wanted to do this with continue, you'd want a second outer loop: http://ideone.com/ofgpK3
label:
while (true) {
for (int i = 0; i < 100; i++) {
System.out.println("i = " + i);
if (i == 99) {
continue label;
}
}
}
A label is nothing like a goto instruction with what you seem to confuse it with. When you continue a program flow to a labeled loop instruction, you only continue its execution by executing its next loop. When you continue at i = 99, you only execute the for loop with the next iteration value i = 100 what renders the loop's condition i < 100 to be false such that the loop terminates.
What you are trying to achieve would require an outer loop such that:
label: while (true) {
for (int i = 0; ; i++) {
if (i % 2 == 0) continue;
if (i == 99) {
continue label;
}
System.out.println("i = " + i);
}
}
}
Note that I removed the condition within the for loop which is now redundant because the explicit jump back into the outer while loop what implicitly causes the inner loop to terminate. This jump restarts the inner loop and therefore causes the counter to reset to i = 0. In general, such explicit program flow is however difficult to read and easy to confuse such that one should avoid it whenever possible for the same reason as one would want to avoid a goto statement of which labels are very lightweight versions of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With