java - if 语句可以嵌套在 while 循环中吗?

标签 java if-statement while-loop do-while

我一直在使用使用 do-while 循环的代码,并且我想在该循环中添加 if else 语句。 do-while 循环检查用户输入的文本,并在输入单词“exit”时结束。

public static void main(String[] args) {

    String endProgram = "exit";
    String userInput;
    java.util.Scanner input = new java.util.Scanner(System.in);

    do {

        userInput = input.nextLine();
        if ( !userInput.equalsIgnoreCase(endProgram) ) {
            System.out.printf("You entered the following: %s", userInput);
        } else

    } while ( !userInput.equalsIgnoreCase(endProgram) );

}

当我尝试编译此代码时,我从命令提示符中收到一条错误消息:

SentinelExample.java:20: error: illegal start of expression
            } while ( !userInput.equalsIgnoreCase(endProgram) );
            ^
SentinelExample.java:22: error: while expected
      }
       ^
SentinelExample.java:24: error: reached end of file while parsing
}
 ^

当我删除循环中的 if else 语句时,程序可以正常编译。我的程序中的语法有问题吗?或者是否可以在 while 循环中放入 if else 语句?

最佳答案

检查您的代码,您是否缺少 else block :

    userInput = input.nextLine();
    if ( !userInput.equalsIgnoreCase(endProgram) ) {
        System.out.printf("You entered the following: %s", userInput);
    } else 

这就是编译错误的原因。您可以通过完全删除 else 来解决此问题,或者如果您想在其中添加某些内容,请执行以下操作:

    userInput = input.nextLine();
    if ( !userInput.equalsIgnoreCase(endProgram) ) {
        System.out.printf("You entered the following: %s", userInput);
    } else {
        // Do something
    }

为了回答您的问题,是的,在 while 循环中嵌套 if 语句是完全有效的。

关于java - if 语句可以嵌套在 while 循环中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18265864/

相关文章:

c - 需要帮助审查计划

Scala 单元类型

java - JFreeChart - OHLC 和普通的 TimeSeries

javascript - 如果 css ("top") 等于或大于 -70(负值)

comparison - 充分使用 'if'语句或 'try/catch' block ?

python - 使用 while 循环查找最小的用户输入数

java - 在 java 中使用 while 循环时出现 Unreachable 语句错误

java - 使用java删除cookie

java - 如何使用 Selenium 运行 Chromium 浏览器?

java - 如何在 Eclipse 中获取 Javafx 9?