In: Computer Science
Java) Write a program to score the rock-paper-scissor game. Each of two users types in either R, P, S or Q to quit. The program then announces the winner as well as the basis for determining the winner: Paper covers rock, Rock breaks scissors, Scissors cut paper, or a Tie game. Allow the user to use lowercase as well as uppercase letters. Your program should loop until the user types a 'Q' to quit.
In the sample code, the game is enclosed within a do…while loop that keeps repeating while the user enters a 'Y' in response to the prompt "Do you want to play again? " The program exits if anything other than an upper-case or lower-case 'Y' is entered. For extra credit, add additional code at the end of the program to keep asking "Do you want to play again? " until the user enters either a 'Y' or 'N' and rejects any other response.(NEEDED)
If you have any doubts, please give me comment...
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
final char ROCK = 'R';
final char PAPER = 'P';
final char SCISSORS = 'S';
final char QUIT = 'Q';
Scanner scnr = new Scanner(System.in);
char choice;
String player2Material = "";
String player1Material = "";
int player1Choice = 0;
int player2Choice = 0;
boolean invalidChoice;
do {
invalidChoice = true;
System.out.println("Play!\nEnter: R (rock), P (paper), S (scissors), Q (Quit)\n");
while (invalidChoice) {
invalidChoice = false;
System.out.print("Player 1 choice: ");
player1Choice = scnr.next().toUpperCase().charAt(0);
switch (player1Choice) {
case ROCK:
player1Material = "rock";
break;
case PAPER:
player1Material = "paper";
break;
case SCISSORS:
player1Material = "scissors";
break;
case QUIT:
System.out.println("Player 1 quit the game");
System.exit(0);
break;
default:
System.out.println("Invalid choice!");
invalidChoice = true;
}
}
invalidChoice = true;
while (invalidChoice) {
System.out.print("Player-2 choice: ");
player2Choice = scnr.next().toUpperCase().charAt(0);
invalidChoice = false;
switch (player2Choice) {
case ROCK:
player2Material = "rock";
break;
case PAPER:
player2Material = "paper";
break;
case SCISSORS:
player2Material = "scissors";
break;
case QUIT:
System.out.println("Player 2 quit the game");
System.exit(0);
break;
default:
System.out.println("Invalid choice!");
invalidChoice = true;
}
}
System.out.println("\nPlayer 1 chooses " + player1Material + ".");
System.out.println("Player 2 chooses " + player2Material + ".");
if (player2Choice == player1Choice) {
System.out.println("Tie!");
} else if ((player2Choice == ROCK && player1Choice == SCISSORS)
|| (player2Choice == PAPER && player1Choice == ROCK)
|| (player2Choice == SCISSORS && player1Choice == PAPER)) {
System.out.println("Player 2 wins!");
} else {
System.out.println("Player 1 wins!");
}
System.out.print("\nDo you want to play again? ");
choice = scnr.next().charAt(0);
} while (choice == 'Y' || choice == 'y');
}
}