-
Notifications
You must be signed in to change notification settings - Fork 113
/
Rock, Paper, Scissors Game
60 lines (48 loc) · 2.22 KB
/
Rock, Paper, Scissors Game
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Create a Random object to generate random moves for the computer
Random random = new Random();
// Possible choices
String[] choices = {"rock", "paper", "scissors"};
// Game introduction
System.out.println("Welcome to Rock, Paper, Scissors!");
System.out.println("Enter your move (rock, paper, or scissors). To exit the game, type 'exit'.");
while (true) {
// Get the player's move
System.out.print("Your move: ");
String playerMove = scanner.nextLine().toLowerCase();
// Check if the player wants to exit the game
if (playerMove.equals("exit")) {
System.out.println("Thanks for playing!");
break;
}
// Validate the player's input
if (!playerMove.equals("rock") && !playerMove.equals("paper") && !playerMove.equals("scissors")) {
System.out.println("Invalid move! Please try again.");
continue;
}
// Get the computer's move
int randomIndex = random.nextInt(3); // Generate a random number between 0 and 2
String computerMove = choices[randomIndex];
// Print the computer's move
System.out.println("Computer's move: " + computerMove);
// Determine the winner
if (playerMove.equals(computerMove)) {
System.out.println("It's a tie!");
} else if ((playerMove.equals("rock") && computerMove.equals("scissors")) ||
(playerMove.equals("paper") && computerMove.equals("rock")) ||
(playerMove.equals("scissors") && computerMove.equals("paper"))) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
System.out.println(); // Add a blank line for better readability
}
// Close the scanner
scanner.close();
}
}