112k views
4 votes
Rock, Paper, Scissors Game Write A Program That Lets The User Play The Game Of Rock, Paper, Scissors Against The Computer. The Program Should Work As Follows 1. Declare A Enumerated Data Type HAND, Which Only Includes Values Of ROCK, PAPER And SCISSOR. Private Static Enum HAND { ROCK, PAPER, SCISSOR }; 2. Write A Static Function Private Static String

User Buhtla
by
8.5k points

1 Answer

1 vote

Final Answer:

```java

import java.util.Random;

import java.util.Scanner;

public class RockPaperScissorsGame {

private static enum HAND { ROCK, PAPER, SCISSOR };

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter your choice (ROCK, PAPER, SCISSOR): ");

HAND userChoice = HAND.valueOf(scanner.next().toUpperCase());

HAND computerChoice = getRandomHand();

System.out.println("Computer's choice: " + computerChoice);

String result = determineWinner(userChoice, computerChoice);

System.out.println(result);

}

private static HAND getRandomHand() {

HAND[] values = HAND.values();

Random random = new Random();

return values[random.nextInt(values.length)];

}

private static String determineWinner(HAND user, HAND computer) {

if (user == computer) {

return "It's a tie!";

} else if ((user == HAND.ROCK && computer == HAND.SCISSOR) ||

(user == HAND.PAPER && computer == HAND.ROCK) ||

(user == HAND.SCISSOR && computer == HAND.PAPER)) {

return "You win!";

} else {

return "Computer wins!";

}

}

}

```

Step-by-step explanation:

The provided Java program implements a simple Rock, Paper, Scissors game where the user plays against the computer. It begins by declaring an enumerated data type `HAND` with values ROCK, PAPER, and SCISSOR. The program then takes the user's input and generates a random choice for the computer. The `determineWinner` function compares the choices and determines the winner based on the rules of the game.

In the `main` method, the user's choice is obtained through the Scanner class, and the computer's choice is generated using the `getRandomHand` function. The result of the game is determined using the `determineWinner` function, and the outcome is printed to the console.

The `getRandomHand` function ensures that the computer's choice is randomly selected from the available options. The game's logic is based on the standard Rock, Paper, Scissors rules, where each element can defeat one and lose to another. The program encapsulates the game's functionality in a concise and readable manner, providing an enjoyable user experience.

User Federico Piazza
by
8.1k points