我对此感到困惑。我们大多数人都听说过Java中没有goto语句。

但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?


当前回答

因为它不受支持,为什么你想要一个什么都不做的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");
     }
}

其他回答

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html

关键字const和goto是 矜持,尽管事实并非如此 目前使用。”

我也不喜欢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的代码可读性强多了,不是吗?

Java关键字列表指定了goto关键字,但它被标记为“未使用”。

它在最初的JVM中(参见@VitaliiFedorenko的回答),但后来被删除了。它可能被保留为一个保留关键字,以防它被添加到Java的后期版本中。

如果goto不在列表中,并且它后来被添加到语言中,使用单词goto作为标识符(变量名、方法名等)的现有代码将被破坏。但是因为goto是一个关键字,这样的代码在当前甚至不会编译,并且它仍然有可能在不破坏现有代码的情况下让它实际做一些事情。

是的,这是可能的,但不像在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");
 }

如何在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