Question: I am trying to make this JAVA GUI program play rock, paper, scissors but am having trouble writing the program to make it do so.
I am trying to make this JAVA GUI program play rock, paper, scissors but am having trouble writing the program to make it do so. Can someone help fix the current program so it can run and play properly? I need it to have a user enter R,P, or S, then press a button "Play!" then have it play against the computer's random play. Finally, it needs to print the result whether the user won, lost or tied. Thank you
//Rock.java import java.util.Random; import java.util.Scanner;
public class Rock { public static void main(String[] args) { String personPlay = ""; // User's play -- "R", "P", or "S" String computerPlay = ""; // Computer's play -- "R", "P", or "S" int computerInt; // Randomly generated number used to determine // computer's play
Scanner scan = new Scanner(System.in); Random generator = new Random();
// Get player's play -- note that this is stored as a string System.out.print("Enter your Play: "); personPlay = scan.next(); // Make player's play uppercase for ease of comparison personPlay = personPlay.trim().toUpperCase(); System.out.println("Person Play:" + personPlay); scan.close();
// Generate computer's play (0,1,2) int min = 0; int max = 2; computerInt = generator.nextInt((max - min) + 1) + min;
// Translate computer's randomly generated play to string switch (computerInt) { case 0: computerPlay = "R"; break; case 1: computerPlay = "P"; break; case 2: computerPlay = "S"; break; default: System.out.println("Invalid computer play. Plase try again."); }
// Print computer's play System.out.println("Computer Play:" + computerPlay);
// here we are cosidering indexes of R,P and S as 0,1 and 2 respectively. // And the least index one is a winner.
// See who won. Use nested ifs instead of &&. if (personPlay.equals(computerPlay)) { System.out.println("It's a tie!"); } else { if (personPlay.equals("R")) { if (computerPlay.equals("P")) { System.out.println("Rock crushes Paper, you win!"); } else { // S System.out.println("Rock crushes Scissors, you win!"); } } else if (personPlay.equals("P")) { if (computerPlay.equals("R")) { System.out.println("Rock crushes Paper, Computer win!"); } else { // S System.out.println("Paper crushes Scissors, User win!"); } } else if (personPlay.equals("S")) { if (computerPlay.equals("R")) { System.out.println("Rock crushes scissors, Computer win!"); } else { // P System.out.println("Paper crushes scissors, Computer win!"); } } } } }
How would I make this run as a GUI where I would press a "Play" button and it plays the game, and prints the winner?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
