*3.17 ( Game: scissor, rock, paper ) Write a program that plays the popular scis
ID: 667506 • Letter: #
Question
*3.17 (Game: scissor, rock, paper) Write a program that plays the popular scissor-rockpaper
game. (A scissor can cut a paper, a rock can knock a scissor, and a paper can
wrap a rock.) The program randomly generates a number 0, 1, or 2 representing
scissor, rock, and paper. The program prompts the user to enter a number 0, 1, or
2 and displays a message indicating whether the user or the computer wins, loses,
or draws. Here are sample runs:
scissor (0), rock (1), paper (2): 1
The computer is scissor. You are rock. You won
scissor (0), rock (1), paper (2): 2
The computer is paper. You are paper too. It is a draw
Explanation / Answer
import java.util.Scanner; // java library to scan user input
import java.util.Random; // java library to generate random numbers
import java.util.*; // java library for using hashmap
/* Java program to play the popular scissor-rockpaper
game.
*/
public class Whowins
{
public static void main(String args[])
{
// Random class is used to generate random numbers
Random random = new Random();
// declare variables
int user;
// declare a generic hashmap having Integer type key and String type value.
Map<Integer, String> hm = new HashMap<>();
// add key-value pair in hashmap as 0-scissor, 1-rock and 2-paper
hm.put(0,"scissor");
hm.put(1,"rock");
hm.put(2,"paper");
//Take input from user
Scanner scanner = new Scanner(System.in);
System.out.print("scissor (0), rock (1), paper (2): ");
user = scanner.nextInt();
// generate random number in the range of 0 to 2
int computer = random.nextInt(3);
// if user and computer are having same outcomes then it is a draw.
if(user == computer)
System.out.print("The computer is "+hm.get(computer)+". You are "+hm.get(user)+" too. It is a draw");
else{
// observe below conditions carefully to understand who wins at what condition.
if(user == 0 && computer == 2)
System.out.print("The computer is "+hm.get(computer)+". You are "+hm.get(user)+". You won");
else if(user == 1 && computer == 0)
System.out.print("The computer is "+hm.get(computer)+". You are "+hm.get(user)+". You won");
else if(user == 2 && computer == 1)
System.out.print("The computer is "+hm.get(computer)+". You are "+hm.get(user)+". You won");
else if(computer == 0 && user == 2)
System.out.print("The computer is "+hm.get(computer)+". You are "+hm.get(user)+". Computer won");
else if(computer == 1 && user == 0)
System.out.print("The computer is "+hm.get(computer)+". You are "+hm.get(user)+". Computer won");
else if(computer == 2 && user == 1)
System.out.print("The computer is "+hm.get(computer)+". You are "+hm.get(user)+". Computer won");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.