In: Computer Science
Create a Java program that allows two players to play Rock,
Paper, Scissors. Player 1 will enter an integer to determine
whether they use rock, paper or scissors. Player 2 will also enter
an integer to determine whether they use rock, paper or scissors.
Use named constants for rock, paper and scissors and set their
values as shown below. Use if-else statements to determine the
results of the game. Use the named constants to compare with the
player 1 and player 2 choices rather than hardcoding the numbers.
Make sure to close your Scanner at the end of your program to avoid
losing a point. When run, the program should look like the
screenshots shown below.
Named constants:
ROCK = 1
PAPER = 2
SCISSORS = 3
Name your Java program RockPaperScissors.java and submit it to
Canvas along with the other files specified in the “Grading”
section below. Make sure your program compiles before submitting it
to avoid losing points.
Example 1:
Player 1 chooses rock.
Player 2 chooses paper.
Player 2 wins!
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 int ROCK = 1;
final int PAPER = 2;
final int SCISSORS = 3;
Scanner scnr = new Scanner(System.in);
String player2Material = "";
String player1Material = "";
int player1Choice = 0;
int player2Choice = 0;
boolean invalidChoice = true;
System.out.println("Play! Enter: 1 (rock), 2 (paper), 3 (scissors)\n");
while (invalidChoice) {
invalidChoice = false;
System.out.print("Player 1 choice: ");
player1Choice = scnr.nextInt();
switch (player1Choice) {
case ROCK:
player1Material = "rock";
break;
case PAPER:
player1Material = "paper";
break;
case SCISSORS:
player1Material = "scissors";
break;
default:
System.out.println("Invalid choice!");
invalidChoice = true;
}
}
invalidChoice = true;
while (invalidChoice) {
System.out.print("Player-2 choice: ");
player2Choice = scnr.nextInt();
invalidChoice = false;
switch (player2Choice) {
case ROCK:
player2Material = "rock";
break;
case PAPER:
player2Material = "paper";
break;
case SCISSORS:
player2Material = "scissors";
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.println();
}
}