Java标签不规则(可能的bug?) [英] Java label irregularity (possible bug?)

查看:144
本文介绍了Java标签不规则(可能的bug?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们查看 Java标准§14.7,我们会看到这些声明可能有标签前缀,例如:

If we look at the Java standard §14.7, we see that statements may have label prefixes, e.g.:


LabeledStatement:

标识符:语句

理论上,标签应该能够标记任何后续语句。因此,例如,以下编译:

In theory, a label should be able to label any succeeding statement. So, for example, the following compiles accordingly:

public class Test {
    public static void main(String[] args) {
    hello:
        return;
    }

}

直观地,这也编译:

public class Test {
    int i;
    public static void main(String[] args) {
        Test t = new Test();
    label:
        t.i = 2;        
    }
}

但以下是 compile:

But the following does not compile:

public class Test {
    public static void main(String[] args) {
    oops:
        int k = 3;  
    }
}

即使这样做(注意范围括号):

Even though this does (note the scoped brackets):

public class Test {
    public static void main(String[] args) {
    oops:
        {
            int k = 3;
        }
    }
}

所以问题取决于是否或不声明是声明。根据标准(以及在线文档):

So the question hinges on whether or not declarations are statements. According to the standard (and the online documentation):


除了表达式语句之外,还有另外两种语句:声明语句和控制流语句。声明语句声明一个变量。

In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements. A declaration statement declares a variable.

我在OSX和Windows上都注意到Java 7和8中的这种行为。这是一个错误还是我误解了标准?

I've noticed this behavior in Java 7 and 8 on both OSX as well as Windows. Is this a bug or am I misunderstanding the standard?

推荐答案

表达式

int k = 3; 

局部变量声明语句

语句 标签声明


LabeledStatement

标识符 Statement

不包含局部变量声明语句。因此,您不能直接在带标签的语句中使用它们。

does not contain local variable declaration statements. You therefore can't use them within a labeled statement directly.

本地变量声明语句可以在blocks 可以在标签声明中使用。

Local variable declaration statements can be used within blocks which can be used within labeled statements.

这篇关于Java标签不规则(可能的bug?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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