使用布尔值从用户字符串java输入验证



我正在创建一个石头剪刀游戏,唯一的问题是输入验证。我尝试过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块无限期迭代,否则,它将在第一次迭代时跳出来。

else块是当输入了不好的条件时执行的块。在循环完成后,系统会被执行

实现这一点的一种更有效或可读的方法是用以下方法代替do-white块:

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(); 
}       
}

我想你只想输入"石头"、"纸"one_answers"剪刀">

只做

if(!input.equals("rock") || !input.equals("paper") || 
!input.equals("scissors")) System.out.println("invalid input");


if(!input.matches("rock|paper|scissors")) System.out.println("invalid input");

相关内容

  • 没有找到相关文章

最新更新