In: Computer Science
JAVA
Remember the childhood game “Rock, Paper, Scissors”? It is a two-players game in which each person simultaneously chooses either rock, paper, or scissors. Rock beats scissors but loses to paper, paper beats rock but loses to scissors, and scissors beats paper but loses to rock. Your program must prompt the player 1 and player 2 to each enter a string for their choice: rock, paper, or scissors. Then appropriately reports if “Player 1 wins”, “Player 2 wins”, or “It is a tie.” Your program should work for both lower case and uppercase letters. If the user string is not rock, scissors or paper the program will print “Wrong choice”.
Sample Run: User input is in Bold.
Player 1: Choose rock, scissors, or paper:
rock
Player 2: Choose rock, scissors, or paper:
paper
Player 2 wins.
Player 1: Choose rock, scissors, or paper:
scissors
Player 2: Choose rock, scissors, or paper:
rock
Player 2 wins.
Player 1: Choose rock, scissors, or paper:
PAPER
Player 2: Choose rock, scissors, or paper:
Rock
Player 1 wins.
Player 1: Choose rock, scissors, or paper:
rock
Player 2: Choose rock, scissors, or paper:
pen
Wrong choice!
import java.util.*;
public class Test {
public static int result(String player1, String
player2){
if(player1.equalsIgnoreCase("rock")
&& player2.equalsIgnoreCase("rock"))
return 0;
else
if(player1.equalsIgnoreCase("rock") &&
player2.equalsIgnoreCase("scissors"))
return 1;
else
if(player1.equalsIgnoreCase("rock") &&
player2.equalsIgnoreCase("paper"))
return 2;
else
if(player1.equalsIgnoreCase("scissors") &&
player2.equalsIgnoreCase("rock"))
return 2;
else
if(player1.equalsIgnoreCase("scissors") &&
player2.equalsIgnoreCase("scissors"))
return 0;
else
if(player1.equalsIgnoreCase("scissors") &&
player2.equalsIgnoreCase("paper"))
return 1;
else
if(player1.equalsIgnoreCase("paper") &&
player2.equalsIgnoreCase("rock"))
return 1;
else
if(player1.equalsIgnoreCase("paper") &&
player2.equalsIgnoreCase("scissors"))
return 2;
else
if(player1.equalsIgnoreCase("paper") &&
player2.equalsIgnoreCase("paper"))
return 0;
return -1;
}
public static void main(String[] args) {
String player1,player2;
Scanner sc=new
Scanner(System.in);
System.out.println("Player 1:
Choose rock, scissors, or paper:");
player1=sc.nextLine();
System.out.println("Player 2:
Choose rock, scissors, or paper:");
player2=sc.nextLine();
if(result(player1,player2)==1){
System.out.println("Player 1 wins");
} else
if(result(player1,player2)==2){
System.out.println("Player 2 wins");
} else
if(result(player1,player2)==0){
System.out.println("It is a tie");
} else {
System.out.println("Wrong choice!");
}
}
}