在java中使用while循环无法访问语句错误 [英] Unreachable statement error using while loop in java
问题描述
可能的重复:
为什么这段代码会给出Unreachable Statement"错误?一个>
这似乎很简单的问题,我在一本书中找到了这个问题.如果有人帮我弄清楚为什么我会出错.
This seems very easy question, I found this question in one book. If anyone help me to figure out why I'm getting error.
do {
System.out.print("inside do");
} while (false);
while (false) { // error
System.out.print("inside while");
}
System.out.print("outside");
我认为,据我所知,输出应该在inside dooutside.但是,它显示编译器错误:无法访问的语句.然后,我试图弄清楚为什么会显示 编译错误:无法访问语句*.所以,我把上面的代码改成这样
I thought, and according to me, output should be inside dooutside. But, it is showing Compiler Error : Unreachable Statement. Then, I tried to figure out, why, it is showing Compilation error : Unreachable Statement* . So, I change the above code like this
boolean i = false;
do {
System.out.print("inside do");
} while (false);
while (i) { // ok
System.out.print("inside while");
}
System.out.print("outside");
现在,它显示了预期的输出,即 inside dooutside .所以,我的问题是 - 第一种和第二种情况有什么不同?另外,当我检查
Now, it is showing expected output i.e. inside dooutside . So, my question is - what makes difference in first and second case ? Also, when I check
if(false){
//something here
}
然后,上面的代码执行没有任何错误.
Then, above code executes without any error.
推荐答案
前两个示例的主要区别在于,在第一种情况下,条件是一个常量,而在第二种情况下则不是.
The main difference between the first two examples is that in the first case, the condition is a constant, whereas in the second it is not.
例如,如果您将 boolean i = false;
更改为 final boolean i = false;
,您将得到相同的编译错误,因为 i 现在是一个常量.
For example, if you change boolean i = false;
into final boolean i = false;
, you will get the same compile error because i is now a constant.
不可达语句的规则定义在JLS 14.21.特别是对 if
有特殊处理,允许 if(DEBUG)
结构,其中 DEBUG
可能是一个常量.
The rules for unreachable statements are defined in the JLS 14.21. In particular there is a special treatment for if
to allow if(DEBUG)
structures where DEBUG
might be a constant.
至于do/while
,里面的语句会执行一次,所以没有问题.
As for the do / while
, the statement inside will be executed once so there is no problem.
这篇相关帖子中有关常量的更多详细信息.
More details about the constants in this related post.
这篇关于在java中使用while循环无法访问语句错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!