【发布时间】:2020-07-30 17:31:37
【问题描述】:
我刚开始学习 Java...对不起,如果这只是一个太愚蠢的问题。
我试图比较用户输入。如果输入不是“是”或“否”,则强制用户输入其中任何一个...但我的代码不起作用...
编译没有问题,但即使输入是“是”或“否”,while 循环也会继续循环。
尝试在循环中打印出“userInput”的值,但输入时正确显示“是”或“否”,但循环仍在继续。
protected static boolean askUser() {
String userInput = "x";
boolean userChoice;
System.out.println("Do you have a question you want to know the answer too? (Yes/No): ");
userInput = input.nextLine();
while (!userInput.equalsIgnoreCase("Yes") || !userInput.equalsIgnoreCase("No")) {
System.out.println("Please input only \"Yes\" or \"No\": ");
userInput = input.nextLine();
}
if (userInput.equalsIgnoreCase("Yes")) {
userChoice = true;
} else {
userChoice = false;
}
return userChoice;
}
关于如何修复此代码的任何想法?
【问题讨论】:
-
检查 do-while 循环
-
!userInput.equalsIgnoreCase("Yes") || !userInput.equalsIgnoreCase("No")始终为真。