我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
当前回答
请注意,您可以将goto的大多数良性用途替换为by
返回 打破 打破标签 扔进去,试着抓住,最后
其他回答
请注意,您可以将goto的大多数良性用途替换为by
返回 打破 打破标签 扔进去,试着抓住,最后
它们被保留以供将来使用(请参阅:Java语言关键字)
关键字const和goto是保留的,即使它们目前没有被使用。
Java中没有goto语句的原因可以在“Java语言环境”中找到:
Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.
当然,它是关键字,但它不在源代码级别上使用。
但如果使用jasmin或其他转换为字节码的低级语言,那么“goto”就在那里
关键字存在,但没有实现。
我能想到的使用goto的唯一好理由是:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
goto outsideloops; // to break out of both loops
}
}
outsideloops:
在Java中,你可以这样做:
loops:
for (int i = 0; i < MAX_I; i++) {
for (int j = 0; j < MAX_J; j++) {
// do stuff
break loops;
}
}
如何在Java中使用"continue"标签的例子是:
public class Label {
public static void main(String[] args) {
int temp = 0;
out: // label
for (int i = 0; i < 3; ++i) {
System.out.println("I am here");
for (int j = 0; j < 20; ++j) {
if(temp==0) {
System.out.println("j: " + j);
if (j == 1) {
temp = j;
continue out; // goto label "out"
}
}
}
}
System.out.println("temp = " + temp);
}
}
结果:
I am here // i=0
j: 0
j: 1
I am here // i=1
I am here // i=2
temp = 1