java - 在打印错误消息后,我如何将用户困在一个循环中,直到给出有效输入?
问题描述
我想询问用户输入,如果它无效,我将推出一个错误语句并要求用户输入另一个输入。我将如何编写一个循环来让用户在收到错误后保持相同的输入请求?我以前使用的方法是 Python 中的 try 和 except。Java中的等价物是什么?
import java.util.Scanner;
import java.util.Random;
public class Main {
//Setting Moves List
enum Move {
ROCK,
PAPER,
SCISSORS
}
//Initiate Scanner and accept user input
public static String getUserMove() {
Scanner keyboard = new Scanner(System.in);
String gesture = keyboard.nextLine();
String userMove = gesture.toUpperCase();
if (userMove.equals("ROCK") || userMove.equals("PAPER") || userMove.equals("SCISSORS")) {
return userMove;
} else {
System.out.println("This is not a valid input." +
"Please try again!");
return "Invalid Input";
}
}
//Get random input as CPU move
public static String getAiMove() {
String Ai;
Random random = new Random();
int input = random.nextInt(3);
if (input == 1) {
Ai = Move.ROCK.name();
} else if (input == 2) {
Ai = Move.PAPER.name();
} else {
Ai = Move.SCISSORS.name();
}
return Ai;
}
//Determine Winner Result
public static void main(String args[]) {
System.out.println("Choose your move against the CPU:");
System.out.println("ROCK, PAPER, OR SCISSORS");
String playerMove = getUserMove();
System.out.println("You threw: " + playerMove);
if (!playerMove.equals("Invalid Input")) {
String cpuMove = getAiMove();
System.out.println("Computer threw: " + cpuMove);
if (playerMove.equals(cpuMove)) {
System.out.println("Tie! Nobody Wins!");
}
// Player is Rock
else if (playerMove.equals(Move.ROCK.name())) {
if (cpuMove.equals(Move.PAPER.name())) {
System.out.println("You Lost! \nPaper beats Rock!");
} else {
System.out.println("You Win! \nRock beats Scissors!");
}
}
// Player is Paper
else if (playerMove.equals(Move.PAPER.name())) {
if (cpuMove.equals(Move.SCISSORS.name())) {
System.out.println("You Lost! \nScissors beats Paper!");
} else {
System.out.println("You Win! \nPaper beats Rock!");
}
}
// Player is Scissors
else {
if (cpuMove.equals(Move.ROCK.name())) {
System.out.println("You Lost! \nPaper beats Rock!");
} else {
System.out.println("You Win! \nRock beats Scissors !");
}
}
}
}
}
解决方案
除了你的 if 语句getUserMove()
,你可以尝试这样的事情,这将强制用户输入一个有效的gesture
.
//Initiate Scanner and accept user input
public static String getUserMove() {
Scanner keyboard = new Scanner(System.in);
String gesture = keyboard.nextLine().toUpperCase();
while(!(userMove.equals("ROCK") || userMove.equals("PAPER") || userMove.equals("SCISSORS"))){
System.out.println("This is not a valid input." + "Please try again!");
gesture = keyboard.nextLine().toUpperCase();
}
return gesture;
}
推荐阅读
- python - Keras load_model 和 get_default_graph.finalize()
- javascript - 当孩子集中注意力时,焦点控制下拉菜单会关闭
- unity3d - 用触摸向各个方向移动玩家?,Unity
- android - 以米为单位获取 TransformableNode 大小
- sql-server - 在插入 SQL Server 中使用 if 条件
- oracle - 为什么我不能从集合(数组)PLSQL 中删除元素
- excel - 计数数据基于帐户参考
- android - 使用 Android Studio 安装 NDK 后缺少二进制文件
- c# - AutoMapper 6.2.2 在映射具有循环引用的对象时抛出 StackOverflowException(尽管相应的属性为 NULL)
- amp-html - 如何在提交到另一个页面时重定向 amp 表单?