This question already has answers here:
while(true); loop throws Unreachable code when isn't in a void

(4个答案)


4年前关闭。




为什么不能在这种类型的for循环之后放置打印语句?我不明白发生了什么。我知道这不是编写for循环的标准方法。所以我正在尝试这段代码,因为我在某处看到了这段代码。我只是不明白为什么您不能在最后放置打印语句。

公开课测试{

public static void main(String [] args){
    for( ; ; ) {
        int x = 0;
        if (x < 5) {
            System.out.print(x + " ");
            x++;
        }
    }
    System.out.println("The End"); //This line will not compile.
}


}

最佳答案

for( ; ; ) is same as while(true),并且由于没有在任何地方创建无限循环而没有中断此循环。

因此,放置在这样的循环之后的任何代码都将永远不会执行(将是无法访问的/死代码),并且编译器会通知您此问题,因为这种情况很可能不是您的意图。

07-24 09:47
查看更多