-1

我知道 goto 是一个在 Java 中没有任何用处的关键字。我可以使用标签或其他方式执行类似的操作以移动到代码的不同部分吗?

    public static void main(String[] args) {
        for(int i=5; i>0; i--){
            System.out.println();

            first:
            for(int x=i; x<6; x++){
                System.out.print("*");
            }
        }
        System.out.println("print '*'");{
            break first;
        }
    }
}
4

3 回答 3

3

你可以这样做

first: {
  for(int i=5; i>0; i--){
    System.out.println();
    if (func(i))
       break first;
    for(int x=i; x<6; x++){
        System.out.print("*");
    }
  }
}
System.out.println("print '*'");
于 2013-08-10T13:04:06.013 回答
2

您可以使用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
j: 0
j: 1
I am here
I am here
temp = 1

但是,我不建议您这样做。有更简洁的方法可以做到这一点,因为James Gosling创建了支持 goto 语句的原始 JVM,但后来他删除了这个不必要的特性。不需要 goto 的主要原因是它通常可以替换为更易读的语句(如 break/continue)或将一段代码提取到方法中。

资料来源:James Gosling,问答环节

于 2013-08-10T13:20:20.123 回答
2

是的,但是没有使用 goto 是有原因的。它是可怕的。但是,如果您只是好奇,这里有一种方法:

http://www.steike.com/code/useless/java-goto/

相反,如果您想以适当的方式做到这一点,请提出您真正的问题并说明您的最终目标,以便我们帮助您设计它。:)

于 2013-08-10T13:08:05.593 回答