相关疑难解决方法(0)

Java中的无限循环

while在Java中查看以下无限循环.它会导致它下面的语句出现编译时错误.

while(true) {
    System.out.println("inside while");
}

System.out.println("while terminated"); //Unreachable statement - compiler-error.
Run Code Online (Sandbox Code Playgroud)

以下相同的无限while循环,但工作正常,并不会发出任何错误,我只是用布尔变量替换条件.

boolean b=true;

while(b) {
    System.out.println("inside while");
}

System.out.println("while terminated"); //No error here.
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,循环后的语句显然无法访问,因为布尔变量b为true,编译器根本不会抱怨.为什么?


编辑:下面的版本while陷入了无限循环,但是对于它下面的语句没有发出编译器错误,即使if循环中的条件总是false因此,循环也永远不会返回并且可以由编译器在编译时本身.

while(true) {

    if(false) {
        break;
    }

    System.out.println("inside while");
}

System.out.println("while terminated"); //No error here.
Run Code Online (Sandbox Code Playgroud)
while(true) {

    if(false)  { //if true then also
        return;  //Replacing return with break fixes the following error.
    }

    System.out.println("inside while");
}

System.out.println("while terminated"); //Compiler-error - unreachable statement. …
Run Code Online (Sandbox Code Playgroud)

java halting-problem

82
推荐指数
5
解决办法
1万
查看次数

在java中使用while循环无法访问的语句错误

可能重复:
为什么此代码出现"无法访问的语句"错误?

这似乎是一个非常简单的问题,我在一本书中找到了这个问题.如果有人帮我弄清楚为什么我会收到错误.

    do {
        System.out.print("inside do");
    } while (false);
    while (false) { // error
        System.out.print("inside while");
    }
    System.out.print("outside");
Run Code Online (Sandbox Code Playgroud)

我想,根据我的说法,输出应该在dooutside里面.但是,它显示编译器错误:无法访问的语句.然后,我试图找出,为什么,它显示编译错误:无法到达的语句*.所以,我改变了上面这样的代码

  boolean i = false;  
  do {
        System.out.print("inside do");
    } while (false);
    while (i) { // ok
        System.out.print("inside while");
    }
    System.out.print("outside");
Run Code Online (Sandbox Code Playgroud)

现在,它显示了预期的输出,即在dooutside内.所以,我的问题是 - 第一和第二种情况有什么不同?另外,当我检查

if(false){ 
  //something here
   }
Run Code Online (Sandbox Code Playgroud)

然后,上面的代码执行没有任何错误.

java if-statement while-loop control-flow unreachable-statement

2
推荐指数
2
解决办法
3390
查看次数