我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
当前回答
因为尽管Java语言不使用它,但JVM字节码使用它。
其他回答
因为它不受支持,为什么你想要一个什么都不做的goto关键字或者一个名为goto的变量?
虽然你可以使用break标签;并继续标签;语句来有效地做goto所做的事情。但我不建议这么做。
public static void main(String [] args) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break");
if (t) {
break second;
}
System.out.println("Not executed");
}
System.out.println("Not executed - end of second block");
}
System.out.println("End of third block");
}
}
不,谢天谢地,Java中没有goto。
goto关键字只保留,但不使用(const也是如此)。
请参阅下面的链接,它显示了所有java保留字,并告诉您添加了哪些版本。
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
Goto是保留的,即使目前没有使用,但永远不要说永远:)
James Gosling创建了支持goto语句的原始JVM,但后来他删除了这个不必要的特性。没有必要使用goto的主要原因是,通常可以用可读性更好的语句(如break/continue)或将一段代码提取到方法中来代替它。
来源:James Gosling,问答环节
是的,这是可能的,但不像在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");
}