(Game: scissor, rock, paper) Write a program that plays the popular scissor-rock
ID: 3793369 • Letter: #
Question
(Game: scissor, rock, paper) Write a program that plays the popular scissor-rock-paper 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 drawExplanation / Answer
The simplest way to do this is using Math.random() method in java. A number is randomly generated using this method as computer input. The generated number is then compared. The user input is taken from the console using Scanner. Then the comparision between user input and the randomly generated number is done using if else condition.
class Game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int user_input;
System.out.println("scissor(0), rock(1), paper(2):");
user_input = input.nextInt();
int computer_input;
String choice1, choice2;
//comparision of randomly generated number (stored in computer_input) with the value less than 2.
computer_input = (int) Math.random()%3+1;
if (computer_input <= 0.33) {
computer_input = 0;
choice1 = "scissor";
}
else if ((computer_input >= 0.34) & (computer_input <= 0.66)) {
computer_input = 1;
choice1 = "rock";
}
else {
computer_input = 2;
choice1 = "paper";
}
//assigning the string "scissor", "rock", "paper" to user_input
if (user_input == 0) {
choice2 = "scissor";
}
else if (user_input == 1) {
choice2 = "rock";
}
else {
choice2 = "paper";
}
if (computer_input > user_input) {
System.out.format( "The computer is %s. You are %s. The computer wins ", choice1, choice2);
computer_input = (int) Math.random();
}
else if (computer_input < user_input) {
System.out.format("The computer is %s. You are %s. You won ", choice1, choice2);
computer_input = (int) Math.random();
}
else if (computer_input == user_input) {
System.out.format("The computer is %s. You are %s too. It's a draw! ", choice2, choice1);
computer_input = (int) Math.random();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.