我一直在使用使用 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/