java - 为什么 BlueJ 给我的代码一个 "unreachable statement"错误?

标签 java while-loop

<分区>

作为我的 APCS 类(class)的一部分,我必须修复已经编写的程序中的小问题,以便以后引用。本节是关于 while 循环的,我从未了解过无法访问的语句,所以我不知道如何修复它。附件是程序中的 while 循环。错误出现在第一个大括号中。

while( false ) {
    //Since the guess doesn't match, determine if it is too low or too high.
    if (userGuess > secretNumber) {
        System.out.print("Guess number " + numGuesses + " is too LOW. ");
    }
    else if (userGuess < secretNumber) {
        System.out.print("Guess number " + numGuesses + " is too HIGH. ");
    }
}

最佳答案

语言规范的特定部分(至少对于 Java 9)是 Sec 14.21 ,它描述了语句被认为不可访问的条件。

特别是:

It is a compile-time error if a statement cannot be executed because it is unreachable.

和(强调我的):

A while statement can complete normally iff at least one of the following is true:

  • The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.

  • There is a reachable break statement that exits the while statement.

The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.

因此,您的 while 循环体被认为是不可访问的,因为表达式的值为 false,并且它是常量。

要修复它,请更改其中任何一个条件;或删除 while 循环,因为它在逻辑上无论如何都不做任何事情。

关于java - 为什么 BlueJ 给我的代码一个 "unreachable statement"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49035037/

相关文章:

c - 终止 While 循环 scanf ("%c",&ch)

Java和android测试方法

java - Gradle构建失败的Android Studio

java - 当使用相应的值代替时如何获取 key ?

c - While 循环使用多个条件过早中断

java - 为什么我的程序在条件为假时进入 while 循环?

java - 为什么 Collections 类中的不可修改方法不使用新元素创建集合?

JavaBeans:如何拥有私有(private)数据?

php - While 循环使用单个 Div 换行值

Java While 循环程序