Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PaperRockScissors.java Write a program that plays the paper-rock-scissors game.

ID: 3791507 • Letter: P

Question

PaperRockScissors.java

Write a program that plays the paper-rock-scissors game.

a. Your program will generate a number 0, 1, or 2 representing scissors, rock, and paper.

b. The program will prompt the user to enter one of the numbers above.

c. Then the program will compare the generated number to the user submitted number and declare the winner.

d. Note that scissors beat paper, paper beats rock, and rock beats scissors.

Sample output:

scissors (0), rock (1), paper (2): 2

You won: Paper beats rock scissors

(0), rock (1), paper (2): 1

You won: Rock beats scissors

Java Program

Explanation / Answer

import java.util.Scanner;


public class PaperRockScissors{

   public static void main(String[] args) {
       // TODO Auto-generated method stub
       boolean flag=true;
       int userChoice=-1;
       Scanner scanner=new Scanner(System.in);
       while(flag){
           //This while loop will ensure that user enters a value between 0 and 2 only
           System.out.print("scissor(0), rock(1), paper(2):");
           userChoice=scanner.nextInt();
           if(userChoice>=2 || userChoice<0){
               System.out.println("Enter a valid number!!");
               //User is prompted to enter a valid value
               continue;
           }
           flag=false;
       }  
       int computerChoice=(int)(Math.random()*10)%3 ;
       //generates a random number between 0 and 2
      
       if(userChoice==0 && computerChoice==1){
           System.out.println("You lost: Rock beats scissors");
       }
       else if(userChoice==1 && computerChoice==2){
           System.out.println("You lost: Paper beats rock");
       }
       else if(userChoice==2 && computerChoice==0){
           System.out.println("You lost: Scissors beats paper");
       }else if(userChoice==1 && computerChoice==0){
           System.out.println("You won: Rock beats scissors");
       }
       else if(userChoice==2 && computerChoice==1){
           System.out.println("You won: Paper beats rock");
       }else if(userChoice==0 && computerChoice==2){
           System.out.println("You won: Scissors beat paper");
       }
       else
           System.out.println("It's a tie");
      
   }

}

Sample runs:

scissor(0), rock(1), paper(2):3
Enter a valid number!!
scissor(0), rock(1), paper(2):0
You lost: Rock beats scissors

scissor(0), rock(1), paper(2):0
It's a tie

scissor(0), rock(1), paper(2):1
You lost: Paper beats rock