我的代码需要一些帮助。我正在尝试修改编写的代码以询问用户“是”或“否”以便循环继续。如果用户输入“是”或“否”以外的任何内容,我应该使用素数读取和while循环来显示错误消息。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declare local variables
String endProgram = "no";
boolean inputValid;
while (endProgram.equals("no")) {
resetVariables();
number = getNumber();
totalScores = getScores(totalScores, number, score, counter);
averageScores = getAverage(totalScores, number, averageScores);
printAverage(averageScores);
do {
System.out.println("Do you want to end the program? Please enter yes or no: ");
input.next();
if (input.hasNext("yes") || input.hasNext("no")) {
endProgram = input.next();
} else {
System.out.println("That is an invalid input!");
}
}
while (!(input.hasNext("yes")) || !(input.hasNext("no")));
}
}
答案 0 :(得分:1)
hasNext
方法调用不带任何参数。看看docs。
因此,您应首先获得输入值:
String response = input.next();
然后测试回复:
!response.equalsIgnoreCase('yes') || !response.equalsIgnoreCase('no')
你可以把这个测试放到一个方法中,因为你多次检查同一个东西。
通过将endProgram
更改为布尔值,可能更容易看到程序的逻辑。甚至可以将其重命名为running
;
boolean running = true;
...
while (running) {
...
String response;
boolean validResponse = false;
while (!validResponse) {
System.out.println("Do you want to end the program? Please enter yes or no: ");
response = input.next();
running = isContinueResponse(response);
validResponse = isValidResponse(response);
if (!validResponse) System.out.println("That is an invalid input!");
}
}