我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
当前回答
因此,如果语言设计者觉得有必要的话,它们是可以被使用的。
此外,如果来自具有这些关键字的语言的程序员(例如。C, c++)错误地使用它们,那么Java编译器可以给出有用的错误消息。
或者只是为了阻止程序员使用goto:)
其他回答
请参阅下面的链接,它显示了所有java保留字,并告诉您添加了哪些版本。
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
Goto是保留的,即使目前没有使用,但永远不要说永远:)
它被认为是不能做的事情之一,但可能被列为保留词,以避免开发人员感到困惑。
如何在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
是的,这是可能的,但不像在c#(在我看来,c#更好!)那些总是模糊软件的观点是愚蠢的!很遗憾java没有至少goto case xxx。
跳转向前:
public static void main(String [] args) {
myblock: {
System.out.println("Hello");
if (some_condition)
break myblock;
System.out.println("Nice day");
}
// here code continue after performing break myblock
System.out.println("And work");
}
向后跳:
public static void main(String [] args) {
mystart: //here code continue after performing continue mystart
do {
System.out.println("Hello");
if (some_condition)
continue mystart;
System.out.println("Nice day");
} while (false);
System.out.println("And work");
}
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.goto
如果有人告诉你Java中没有goto语句,那你就被骗了。事实上,Java由两层“源代码”组成。