有人可以告诉我为什么编译器说下面的代码中缺少标签:
案例1:
错误:标签丢失
void crazyLoop() {
int c = 0;
JACK: while (c < 8) {
JILL: System.out.println(c);
if (c > 3)
break JILL;
else
c++;
}
}
此处 JILL
是可访问的,因为我已在 JACK
内声明 JILL
,而不是在 JACK
外部。
案例2:
错误: c 无法解析。 如果我这样做:
void crazyLoop() {
JILL:int c = 0;
JACK: while (c < 8) {
System.out.println(c);
if (c > 3)
break JILL;
else
c++;
}
}
编译器说c
无法解析为变量。
有人可以解释一下发生了什么吗?
最佳答案
from JSL 14.15. The break Statement
A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label
所以错误是由break语句没有引用循环的标签引起的。 此外,只有语句可以有标签前缀。 see documentation
以下代码编译成功:
void crazyLoop() {
int c = 0;
ILL:
c= 0;
JACK: while (c < 8) {
System.out.println(c);
if (c > 3)
break JACK;
else
c++;
}
关于java - 即使标签位于封闭循环内,中断标签也会丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40528792/