错误:未定义标签,如何在Java中的此代码中使用label语句? [英] error:undefined label, how to use label statement in this code in java?

查看:515
本文介绍了错误:未定义标签,如何在Java中的此代码中使用label语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java教科书中读到,任何语句都可以标记并且可以与break一起使用. 但是,在尝试这段代码时,我得到了错误的未定义标签. (stackoverflow的家伙在将该问题标记为重复之前等待,我已经检查了这些问题,但没有一个解释这个问题.)

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.

因此,在您的情况下,标签first的范围是标签后面的sysout语句.更清楚地说,您可以使用卷曲括号定义范围,并在这些括号内将其有效范围更改为跳转到标签.所以下面是有效的

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

这篇关于错误:未定义标签,如何在Java中的此代码中使用label语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆