I'm making a simple rock paper scissors program but am unsure how to ensure that the user only enters a valid choice. I need to be able to reprompt them if they don't type some varriant of "rock", "paper", or "scissors" (capitalization doesn't matter) and later "yes" or "no". Suggestions?
import java.util.*;
public class RockPaperScissors {
private int wins = 0;
private int losses = 0;
private int ties = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
RockPaperScissors model = new RockPaperScissors();
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Rock, Paper, Scissors... Pick one! (Type Rock, Paper, or Scissors)");
String playerChoice = scan.next();
String computerChoice = model.getRandomChoice();
System.out.println("You chose " + playerChoice + ".");
System.out.println("The computer chose " + computerChoice + ".");
RockPaperScissors.GameOutcome outcome = model.getGameOutcome(
playerChoice, computerChoice);
if (outcome == RockPaperScissors.GameOutcome.WIN) {
System.out.println("You won! Congratulations");
} else if (outcome == RockPaperScissors.GameOutcome.LOSE) {
System.out.println("You lose! Better luck next time!");
} else {
System.out.println("Tie!");
}
System.out.print("Do you want to play again? (Yes/No):");
String answer = scan.next();
if (answer.equalsIgnoreCase("no")) {
break;
}
}
System.out.println("Thanks for playing!");
System.out.println("Wins: " + model.getWins());
System.out.println("Losses: " + model.getLosses());
System.out.println("Ties: " + model.getTies());
scan.close();
}
public static enum GameOutcome {
WIN, LOSE, TIE;
}
public GameOutcome getGameOutcome(String userChoice, String computerChoice) {
if (userChoice.equalsIgnoreCase("Rock")) {
if (computerChoice.equalsIgnoreCase("Paper")) {
losses++;
return GameOutcome.LOSE;
} else if (computerChoice.equalsIgnoreCase("Scissors")) {
wins++;
return GameOutcome.WIN;
}
} else if (userChoice.equalsIgnoreCase("Paper")) {
if (computerChoice.equalsIgnoreCase("Scissors")) {
losses++;
return GameOutcome.LOSE;
} else if (computerChoice.equalsIgnoreCase("Rock")) {
wins++;
return GameOutcome.WIN;
}
} else if (userChoice.equalsIgnoreCase("Scissors")) {
if (computerChoice.equalsIgnoreCase("Rock")) {
losses++;
return GameOutcome.LOSE;
} else if (computerChoice.equalsIgnoreCase("Paper")) {
wins++;
return GameOutcome.WIN;
}
}
ties++;
return GameOutcome.TIE;
}
public String getRandomChoice() {
double d = Math.random();
if (d < .33) {
return "Rock";
} else if (d < .66) {
return "Paper";
} else {
return "Scissors";
}
}
public int getWins() {
return wins;
}
public int getLosses() {
return losses;
}
public int getTies() {
return ties;
}
}