This question already has answers here:
What is this error mean label z is missing in break statement? [duplicate]
                                
                                    (3个答案)
                                
                        
                5年前关闭。
            
        

package brea;

public class BreakExample {

    static String o ="";
    public static void main(String[] args) {
        z:
        o = o +2;
    for(int x = 3 ; x < 8 ; x++){
        if(x == 4) break;
        if(x==6) break z;
        o = o+x;
    }
        System.out.println(o);
    }
}


在上面的代码中,由于缺少标签z,我收到了编译错误。是什么原因 ?有什么解决方案?

最佳答案

A label is followed by a statement。就您而言,该陈述只是

o = o + 2;


因此,z仅在该语句的范围内。


  带标签的语句的标签范围是立即
  包含的声明。


如果希望zfor语句的范围内,请添加一个block语句

z: {
    o = o + 2;
    for (int x = 3; x < 8; x++) {
        if (x == 4)
            break;
        if (x == 6)
            break z;
        o = o + x;
    }
}

10-06 13:32
查看更多