java的while会错,在java中使用while循环时出现无法访问的语句错误

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");

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");

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.

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.

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Javawhile循环语句是一种常见的循环控制结构,用于重复执行一段代码,直到指定的条件不再满足为止。while循环语句的基本语法如下所示: ``` while (condition) { // 循环体代码 } ``` 其,`condition`是一个布尔表达式,表示循环条件。只要`condition`的值为`true`,就会重复执行循环体代码。当`condition`的值为`false`,循环就会终止。 下面是一个简单的示例,演示了如何使用while循环语句来计算1到10的整数之和: ``` int sum = 0; int i = 1; while (i <= 10) { sum += i; i++; } System.out.println("1到10的整数之和是:" + sum); ``` 上面的代码,`sum`变量用于存储1到10的整数之和。`i`变量用于控制循环次数,初始值为1。在每次循环,先将`i`加到`sum`,然后将`i`的值加1,直到`i`的值大于10为止。 另外,Java还有一种类似的循环语句叫做do...while循环语句。它的语法与while循环语句有所不同,具体如下: ``` do { // 循环体代码 } while (condition); ``` do...while循环语句先会执行一次循环体代码,然后再判断循环条件是否满足。只要循环条件满足,就会继续执行循环体代码,直到循环条件不再满足为止。 下面是一个简单的示例,演示了如何使用do...while循环语句来输入一个整数,直到输入的值为0为止: ``` Scanner scanner = new Scanner(System.in); int num; do { System.out.print("请输入一个整数(输入0结束):"); num = scanner.nextInt(); } while (num != 0); System.out.println("输入结束。"); ``` 上面的代码使用Scanner类从控制台读取整数,然后使用do...while循环语句判断输入的值是否为0。只要输入的值不为0,就会继续输入,直到输入的值为0为止。最后输出“输入结束”。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值