Project2 1v RockPaperScissorsGame
Project2 1v RockPaperScissorsGame
Features
Supports Rock, Paper, Scissors choices
Randomized computer moves
Looped gameplay until the player decides to exit
Score tracking (optional enhancement)
Source Code:→
import java.util.Random;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
// Get user input
System.out.print("\nEnter rock, paper, or scissors (or 'exit' to quit): ");
// Exit condition
if (userChoice.equals("exit")) {
System.out.println("Thanks for playing! Goodbye!");
break;
}
// Validate user input
if (!userChoice.equals("rock") && !userChoice.equals("paper") &&
!userChoice.equals("scissors")) {
// Computer's choice
String computerChoice = choices[random.nextInt(3)];
// Determine winner
if (userChoice.equals(computerChoice)) {
System.out.println("It's a tie!");
}
else if (
(userChoice.equals("rock") &&
computerChoice.equals("scissors")) ||
(userChoice.equals("paper") &&
computerChoice.equals("rock")) ||
(userChoice.equals("scissors") &&
computerChoice.equals("paper"))
){
System.out.println("You win! ");
} else {
System.out.println("You lose! ");
}
}
scanner.close();
}
}
How It Works
1. The user enters "rock", "paper", or "scissors".
2. The computer randomly selects one of the three choices.
3. The program compares the choices and determines the winner.
4. The game runs in a loop until the user types "exit".
In Java, the Random class, located within the java.util package, is used to
generate pseudo-random numbers of different data types like integers,
doubles, floats, and longs, essentially providing a way to create seemingly
unpredictable values within your program; you can create a Random object
and use its methods to retrieve these random values based on a seed value that
determines the sequence of generated numbers.
Key points about the Random class:
• Purpose: To generate random numbers for various applications like
shuffling lists, simulating events, or creating randomized tests.
• How it works: The Random class uses a mathematical algorithm to
produce a sequence of numbers that appear random but are actually
based on an initial "seed" value.
Common methods: