问题描述
我一直以为标签必须只用于循环,但似乎没有。给出这样的代码:
I always thought that the labels must be used only with loops but it seems not. Giving such code:
public class LabelTest {
public static void main(String[] args) {
label1: System.out.println("");
label2: LabelTest t = new LabelTest();
}
}
当标记为label1的编译行编译但代码在label2给出错误。为什么?为什么我要标记不是循环的语句?
When compiled line labeled "label1" compiles but the code at "label2" gives errors. Why's that? And why would I want to label statements which are not "loops"?
推荐答案
由于无法应用标签而出现错误变量声明,这就是如何定义(a label只能在 Statement
之前,而 LocalVariableDeclarationStatement
不是 Statement
)。原因可能是它可能导致关于变量范围的混淆。这有效:
You get an error because a label cannot be applied to variable declarations, that's just how the language grammar is defined (a label can only precede a Statement
, and a LocalVariableDeclarationStatement
is not a Statement
). The reason is probably that it could cause confusion concerning variable scope. This works:
label1: System.out.println("");
label2: { LabelTest t = new LabelTest(); }
这篇关于在没有“循环”的java中使用标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!