Write a program that plays the RockPaper-Scissors game. When played between two
ID: 3682807 • Letter: W
Question
Write a program that plays the RockPaper-Scissors game. When played between two people, each person picks one of three options at the same time, and a winner is determined: Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. The program should randomly choose one of the three options without revealing it to the user and then prompt for the user's selection. At that point the program reveals its choice and prints a statement indication if the computer won, the user won, or if it was a tie. Continue playing until the user chooses to stop, then print the number of user wins, losses, and ties. the player enters Q to quit. and P,R,S for paper, rock and, scissors.
Explanation / Answer
import java.util.Scanner;
import java.lang.String;
import java.util.Random;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int playerScore = 0;
int computerScore = 0;
String playerHand="",computerHand="";
boolean flag=true;
while (true)
{
System.out.println("Input "rock", "paper", or "scissors" ("q" to quit): ");
playerHand = scan.next();
if ( !( playerHand.equals("rock")
|| playerHand.equals("paper")
|| playerHand.equals("scissors")
|| playerHand.equals("q")))
{
flag = false;
}
while (!flag) {
System.out.println("Invalid input!! (Input "rock", "paper"," +
""scissors", or "q")");
playerHand = scan.next();
// Check new input is valid
if ( playerHand.equals("rock")
|| playerHand.equals("paper")
|| playerHand.equals("scissors")
|| playerHand.equals("q"))
{
flag = true;
}
}
if (playerHand.equals("q"))
{
System.out.println("Your game ends here. Results are:");
System.out.println("Your score:"+playerScore +" Computer Score :"+computerScore);
return;
}
int tempHand = rand.nextInt(3);
switch (tempHand)
{
case 0:
computerHand = "rock";
break;
case 1:
computerHand = "paper";
break;
case 2:
computerHand = "scissors";
break;
}
if (playerHand.equals(computerHand))
{
System.out.println("Tie");
}
else
{
switch (computerHand)
{
case "rock":
if (playerHand.equals("paper"))
{
System.out.println("Paper beats Rock");
playerScore++;
}
else if (playerHand.equals("scissors"))
{
System.out.println("Rock beats Scissors");
computerScore++;
}
break;
case "paper":
if (playerHand.equals("rock"))
{
System.out.println("Paper beats Rock");
computerScore++;
}
else if (playerHand.equals("scissors"))
{
System.out.println("Scissors beats Paper");
playerScore++;
}
break;
case "scissors":
if (playerHand.equals("rock"))
{
System.out.println("Rock beats Scissors");
playerScore++;
}
else if (playerHand.equals("paper"))
{
System.out.println("Scissors beats Paper");
computerScore++;
}
break;
}
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.