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

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


当前回答

它被认为是不能做的事情之一,但可能被列为保留词,以避免开发人员感到困惑。

其他回答

请注意,您可以将goto的大多数良性用途替换为by

返回 打破 打破标签 扔进去,试着抓住,最后

关键字存在,但没有实现。

我能想到的使用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;
    }
}

是的,这是可能的,但不像在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保留字,并告诉您添加了哪些版本。

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

Goto是保留的,即使目前没有使用,但永远不要说永远:)

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