In: Computer Science
In a Java program, how could I write a program that can assign values that would make a rock paper scissors game work? I have a program that will generate a computer response of either rock, paper, or scissors but how can I compare a user input of "rock", "paper", or "scissors" so that we can declare either the user or the computer the winner.
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissor {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Initialising Scanner object
Random rand = new Random(); // Initialising Random object
int comGenerated = 1 + rand.nextInt(3); //Initialising comGeneratedn ,
//1: Rock, 2: paper, 3: Scissors
System.out.print("Pick yours\n1 for 'rock', 2 for 'paper', 3 for 'scissors':\nEnter Your Input : ");
int userInput = sc.nextInt(); // Taking input userInput
String userInputText;
//converting user input number to string
switch (userInput) {
case 1: userInputText = "rock";
break;
case 2: userInputText = "paper";
break;
default: userInputText = "scissor";
break;
}
while(userInput != 1 && userInput != 2 && userInput != 3){ //checking for wrong user input
System.out.println("WRONG user input, try again");
userInput = sc.nextInt();
}
if(comGenerated == userInput){ //Checking for who won the match
System.out.println("Computer:"+userInputText+" & You: "+userInputText+"\nGame Ties");
}else if(comGenerated == 1 && userInput==2){
System.out.println("Computer: rock & You: paper\nYou WON");
}else if(comGenerated == 1 && userInput==3){
System.out.println("Computer: rock & You: scissor\nComputer WON");
}else if(comGenerated == 2 && userInput==1){
System.out.println("Computer: paper & You: rock\nComputer WON");
}else if(comGenerated == 2 && userInput==3){
System.out.println("Computer: paper & You: scissor\nYou WON");
}else if(comGenerated == 3 && userInput==1){
System.out.println("Computer: scissor & You: rock\nYou WON");
}else if(comGenerated == 3 && userInput==2){
System.out.println("Computer: scissor & You: paper\nComputer WON");
}
System.out.println("Game finished! Want to play again?\n[Y] Play again [Any other key] Exit ");
char playAgain = sc.next().charAt(0);
if(playAgain == 'Y' || playAgain == 'y')
main(args);
}
}
Program Snapshot
SAMPLE OUTPUT
ANOTHER SAMPLE OUTPUT