java未定义的标签outer,错误:未定义标签,如何在Java中的此代码中使用label语句?...

I read in textbooks for Java that any statement can be labeled and can be used with break.

But while trying this code i get error undefined label. (Guys at stackoverflow wait before marking this question as duplicate, i have checked those questions but none of those explain this problem).

public class LabelTest {

public static void main(String[] args) {

first: System.out.println("First statement");

for (int i = 0; i < 2; i++) {

System.out.println("Second statement");

break first;

}

}

}

解决方案

The scope of a label of a labeled statement is the immediately

contained Statement.

So in your case, the scope of lable first is the sysout statement following the lable. To be clearer, you can define the scope using curly braces, and within these braces its valid to jump to the label. So below are valid

first: {

System.out.println("First statement");

for (int i = 0; i < 2; i++) {

System.out.println("Second statement");

break first;

}

}

OR

first: {

System.out.println("First statement");

break first;

}

second:

for(int i=0;i<2;i++){

System.out.println("Second statement");

break second;

}