我想请求用户输入一个输入,如果它无效,我将推出一个错误语句,并请求用户输入另一个输入。我该如何编写一个循环,在给定错误后将用户保持在相同的输入请求中?我以前使用的方法都是try和except在python中。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 !");
}
}
}
}
}
2条答案
按热度按时间9nvpjoqh1#
将getusermove方法更改为below:-
bhmjp9jg2#
而不是你的if语句
getUserMove()
,您可以尝试这样的操作,这将强制用户输入有效的gesture
.