gpt4 book ai didi

java - 使用 boolean 值从用户字符串 java 输入验证

转载 作者:行者123 更新时间:2023-12-01 17:45:42 25 4
gpt4 key购买 nike

我正在创建一个石头剪刀布游戏,唯一让我困惑的部分是输入验证。我尝试过 do/while 循环、try/catch 但似乎无法让它正常运行。以下是我目前拥有的 getUserChoice 方法。任何帮助将不胜感激。谢谢!

public String getUserChoice(){
String user = " ";
boolean error = false;

Scanner in = new Scanner(System.in);
System.out.println("Please enter rock, paper, or scissors: ");
user = in.nextLine(); //reads user input

do {
if (user.equalsIgnoreCase("rock")) {
user = "rock";
error = false;
}
else if (user.equalsIgnoreCase("paper")) {
user = "paper";
error = false;
}
else if (user.equalsIgnoreCase("scissors")) {
user = "scissors";
error = false;
}
}
while(error); {
System.out.println("Please enter valid input: ");
}
return user;
}

最佳答案

您可以将代码稍微更改为:

public String getUserChoice(){
String user = " ";
boolean error = true;

Scanner in = new Scanner(System.in);
System.out.println("Please enter rock, paper, or scissors: ");
user = in.nextLine(); //reads user input

do {
if (user.equalsIgnoreCase("rock")) {
user = "rock";
error = false;
}
else if (user.equalsIgnoreCase("paper")) {
user = "paper";
error = false;
}
else if (user.equalsIgnoreCase("scissors")) {
user = "scissors";
error = false;
} else {
System.out.println("Please enter valid input: ");
user = in.nextLine();
}
}
while(error);

return user;
}

boolean error = true; 使 while block 无限迭代,否则,它将在第一次迭代时跳出。

else block 是在输入条件不佳时执行的内容。 while 之外的 system.out 在循环结束后执行

实现此目的的更有效或可读的方法是将 do-while block 替换为:

while (true){
if (user.equalsIgnoreCase("rock") || user.equalsIgnoreCase("paper") || user.equalsIgnoreCase("scissors")){
return user;
} else {
System.out.println("Please enter valid input: ");
user = in.nextLine();
}
}

关于java - 使用 boolean 值从用户字符串 java 输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60870790/

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