/* This program plays paper, scissors, rock with the user with the computer making its choices randomly. The program runs in a loop while the user types yes. Example of do .. while loop and switch statements */ import java.util.*; public class PaperScissorsRock { // constants for paper, scissors, and rock private final static int SCISSORS = 0; private final static int ROCK = 1; private final static int PAPER = 2; public static void main(String[] args) { Scanner kbd = new Scanner(System.in); Random rand = new Random(); // for computer's choice int user = 0, computer = 0; // the players String response; do { // get user's choice of p, s, r System.out.print("Choose P, S, R: "); String choice = kbd.nextLine(); // translate into constant integers if (choice.equalsIgnoreCase("s")) user = SCISSORS; else if (choice.equalsIgnoreCase("r")) user = ROCK; else if (choice.equalsIgnoreCase("p")) user = PAPER; // computer makes random choice computer = rand.nextInt(3); System.out.print("Computer chooses "); System.out.println(PSR(computer)); // determine whether user or computer wins switch (user - computer) { case 0 : System.out.println("Tie"); break; case 1 : case -2 : System.out.println("You win"); break; case 2 : case -1 : System.out.println("Computer wins"); break; } System.out.print("Play again (y/n)? "); response = kbd.nextLine(); // loop while user answers yes // note: user input should really be validated here } while(response.equalsIgnoreCase("y") || response.equalsIgnoreCase("yes")); } private static String PSR(int i) { // translate constant int code into string String str; switch (i) { case PAPER : str = "paper"; break; case SCISSORS : str = "scissors"; break; case ROCK : str = "rock"; break; default : str = ""; } return str; } }