gpt4 book ai didi

java - 需要帮助修改输入验证和错误消息的代码

转载 作者:行者123 更新时间:2023-12-01 10:57:24 25 4
gpt4 key购买 nike

我的代码需要一些帮助。我正在尝试修改书面代码以询问用户"is"或“否”以便循环继续。如果用户输入"is"或“否”以外的任何内容,我应该使用主要读取和 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")));
}
}

最佳答案

hasNext 方法调用不带任何参数。看看docs .

因此您应该首先获取输入的值:

String response = input.next();

然后测试响应:

!response.equalsIgnoreCase('yes') || !response.equalsIgnoreCase('no')

您可以将此测试放入一个方法中,因为您多次检查同一事物。

endProgram 更改为 boolean 值可能会更容易查看程序的逻辑。甚至可能将其重命名为 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!");
}
}

关于java - 需要帮助修改输入验证和错误消息的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33559814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com