Write a Java program that allows the user to play the game or Rock, Paper Scisso
ID: 3744328 • Letter: W
Question
Write a Java program that allows the user to play the game or Rock, Paper Scissors 5 times. Remember: Rock crushes scissors, Scissors cuts paper, Paper hides rock.
Enter 1 for Rock, 2 for Paper, 3 for Scissors
1 Player picked Rock, Computer Paper. Computer wins Enter 1 for Rock, 2 for Paper, 3 for Scissors 2 Player picked paper, Computer Scissors. Computer wins Enter 1 for Rock, 2 for Paper, 3 for Scissors 3 Player picked Scissors, Computer Paper. Player wins Enter 1 for Rock, 2 for Paper, 3 for Scissors 1 Tie Enter 1 for Rock, 2 for Paper, 3 for Scissors 2 Player picked paper, Computer Scissors. Computer wins
Computer wins: 3 Player wins: 1
here an example
computer = (int)(Math.random() * 3) + 1; //computer choice
System.out.println("Enter 1 for Rock, 2 for Paper, 3 for Scissors");
player = reader.nextInt(); //player choice
//Complete the code to determine who wins and add to computer or player score
//Rock crushes scissors, paper hides rock, scissors cuts paper
// if player is equal to computer => tie
// if player picks Rock then
// if computer choice is paper, computer wins
// if computer choice is scissors, player wins
// otherwise if player picks paper then
// if computer choice is rock,player wins
// if computer choice is scissors, computer wins
// otherwise if player picks scissors then
// if computer choice is rock, computer wins
// if computer choice is paper, player wins
// otherwise, the player picked an invalid choice. Do not count the game.
//End of loop here.
//print number of computer wins and player wins
Explanation / Answer
import java.util.Random; import java.util.Scanner; public class RockPaperScissors { public static int whoWins(int ch1, int ch2) { if((ch1 == 1 && ch2 == 3) || (ch1 == 2 && ch2 == 1) || (ch1 == 3 && ch2 == 2)) { return 1; } else { return 2; } } public static String getChoice(int n) { if(n == 1) { return "Rock"; } else if(n == 2) { return "Paper"; } else { return "Scissors"; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); Random random = new Random(); int cWins = 0, pWins = 0; for(int i = 0; i < 5; ++i) { int computer = 1 + random.nextInt(3); System.out.print("Enter 1 for Rock, 2 for Paper, 3 for Scissors "); int player = in.nextInt(); System.out.printf("Player picked %s, Computer %s. ", getChoice(player), getChoice(computer)); if (computer == player) { System.out.println("Tie"); } else { int winner = whoWins(computer, player); if (winner == 1) { System.out.println("Computer wins"); cWins++; } else if (winner == 2) { System.out.println("Player wins"); pWins++; } } } System.out.println("Computer wins: " + cWins); System.out.println("Player wins: " + pWins); } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.