我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
当前回答
如何在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
其他回答
因为它不受支持,为什么你想要一个什么都不做的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");
}
}
请注意,您可以将goto的大多数良性用途替换为by
返回 打破 打破标签 扔进去,试着抓住,最后
我也不喜欢goto,因为它通常会降低代码的可读性。然而,我相信这条规则也有例外(特别是涉及词法分析器和解析器时!)
当然,你也可以把程序转换成类似于汇编程序的形式,然后编写类似于
int line = 1;
boolean running = true;
while(running)
{
switch(line++)
{
case 1: /* line 1 */
break;
case 2: /* line 2 */
break;
...
case 42: line = 1337; // goto 1337
break;
...
default: running = false;
break;
}
}
(所以你基本上写了一个执行二进制代码的虚拟机…其中line对应于指令指针)
这比使用goto的代码可读性强多了,不是吗?
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
关键字const和goto是 矜持,尽管事实并非如此 目前使用。”
不,谢天谢地,Java中没有goto。
goto关键字只保留,但不使用(const也是如此)。