Reputation: 21
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
Upvotes: 0
Views: 1265
Reputation: 5173
The JLS says:
The Identifier is declared to be the label of the immediately contained Statement. ... Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with
break
orcontinue
statements ... appearing anywhere within the labeled statement.
The scope of a label of a labeled statement is the immediately contained Statement.
In your case the for-loop immediatly follwoing the label runing
doesn't mention the label. The second for loop tries to continue to the label. But it is not part of the first for-loop, thus the immendiatly following statement.
This results in a compile-time error.
Thus in order to syntactically correct jump from one for loop to another for loop using label you need an outer loop containing the label. But I would argue that's not the right approach.
Upvotes: 3
Reputation: 63955
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.
Upvotes: 2
Reputation: 676
As LuCio has already stated, the problem here is that the second loop is not part of the first loop.
If you nest the for
loops from your example it will work:
public static void main(String[] args) {
runing:
for (int i = 1; i < 10; i++) {
System.out.print(i);
for (int j = 1; j < 10; i++) {
if (j == 5) {
continue runing;
}
}
}
}
Of course this is just an example of how it could work, i'm not sure if this is the actual logic your application requires.
Upvotes: 0