when i am trying to access for loop from another loop i get following errors. how can i do that can somebody explain.
public class Test {
public static void main(String...rDX) {
runing:
for (int i = 1; i < 10; i++)
System.out.print(i);
for(int i = 1; i < 10; i++) {
if (i == 5) {
continue runing;
}
}
}
}
error: java:28: error: undefined label: runing continue runing; ^ 1 error
You can't do that because you can only abort a chain of nested for
s and continue on some outer / parent for
. You can't continue with other for
s that happen to be simply nearby. But you could use that to do e.g.
public class Test {
public static void main(String...rDX) {
runing: for (;;) { // infinite loop
for (int i = 1; i < 10; i++)
System.out.print(i);
for(int i = 1; i < 10; i++) {
if (i == 5) {
continue runing;
}
}
break; // = break runing; effectively never reached
// because above "continue" will always happen
}
}
}
This has the desired(?) effect since it continues with the newly added outer loop which goes back the the first loop.
(?) = at least what it would do when it would compile - I doubt you actually want that because you'll still print 1..10, then in the next step invisibly count to 5 and do nothing with that number.