error:undefined label, how to use label statement in this code in java?

别来无恙 提交于 2019-12-12 12:15:34

问题


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;
        }
    }
}

回答1:


As per JLS 14.7

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;
}


来源:https://stackoverflow.com/questions/18159965/errorundefined-label-how-to-use-label-statement-in-this-code-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!