retry: {
.........
if(xyz < 5) {
continue retry;
}
}
Problem : continue cannot be used outside of a loop
Why iteration of a block is prevented in java?
retry: {
.........
if(xyz < 5) {
continue retry;
}
}
Problem : continue cannot be used outside of a loop
Why iteration of a block is prevented in java?
It's not supported because noone implemented it, presumably because they thought that, well, loops should be implemented with the loop constructs Java provides.
What you want to do can easily be implemented as a while
loop if you invert the condition and use break instead:
while (true) {
.........
if(xyz >= 5) {
break;
}
}
Or why not write it as a regular loop without break
or continue
?
do {
.........
} while (xyz < 5);
Problem : continue cannot be used outside of a loop
continue
is used within a loop i.e. for/while/do-while
, if
statements are conditional code blocks and not loops.
Learn more about code branching statements here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
The purpose of continue
keyword is to skip rest of the code inside loop to start with the next pass of loop. So, by it's purpose, continue would not fit in the contexts outside the loops.
goto
could be other option for you to reset (or restart) the code of execution. However the best way could be move such part into a method and use recursion along with return
under specific conditions to achieve the purpose you are talking about.
As others have pointed out, labels in Java label loops, and are used to specify which loop to break
or continue
.
That said, if you really want to write "spaghetti code" you can misuse break and continue like for instance:
public class SillyGotoExmple {
public static void main(String args[]) {
int count, loops;
final int NUM_LOOPS=2;
final int MAX_COUNT=10;
loops=0;
bar: do {
count = 0;
foo: do {
System.out.println(count);
if(++count < MAX_COUNT) {
continue foo;
} else if(++loops < NUM_LOOPS) {
continue bar;
} else {
break bar;
}
} while (true);
} while(true);
}
}
For some more discussion on goto
in Java, see e.g. Is there a goto statement in Java?