我正在创建一个石头剪刀布游戏,唯一挂断的就是输入验证。我尝试过do / while循环,try / catch,但似乎无法使其正常运行。以下是我目前对getUserChoice方法所拥有的内容。任何帮助将不胜感激。谢谢!
struct h_node
答案 0 :(得分:0)
我想您只想输入“ rock”,“ paper”和“ scissors”
只做
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");
答案 1 :(得分:0)
您可以将代码稍微更改为:
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
块将被执行。循环完成后,一会儿就会执行system.out
一种更有效或更易实现的方法是用以下方式替换do-while块:
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();
}
}