-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRockPaperScissors.java
More file actions
52 lines (44 loc) · 1.69 KB
/
Copy pathRockPaperScissors.java
File metadata and controls
52 lines (44 loc) · 1.69 KB
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
import java.util.*;
public class RockPaperScissors {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to Rock Paper Scissors!");
playGame();
}
public static void playGame() {
String playerChoice = getPlayerInput();
char computerChoice = getRandomChoice();
System.out.println("Computer's choice: " + computerChoice);
if (playerChoice.equals(String.valueOf(computerChoice))) {
System.out.println("It's a tie!");
} else if (isWin(playerChoice.charAt(0), computerChoice)) {
System.out.println("You win!");
} else {
System.out.println("Computer wins!");
}
}
public static boolean isWin(char playerChoice, char computerChoice) {
if ((playerChoice == 'r' && computerChoice == 's') ||
(playerChoice == 's' && computerChoice == 'p') ||
(playerChoice == 'p' && computerChoice == 'r')) {
return true;
}
return false;
}
public static String getPlayerInput() {
System.out.println("Enter 'r' for rock, 'p' for paper, 's' for scissors");
while (true) {
String input = scanner.nextLine().trim().toLowerCase();
if (input.equals("r") || input.equals("p") || input.equals("s")) {
return input;
} else {
System.out.println("Invalid input. Please enter 'r', 'p', or 's'.");
}
}
}
public static char getRandomChoice() {
Random random = new Random();
int rand = random.nextInt(3);
return rand == 0 ? 'r' : rand == 1 ? 'p' : 's';
}
}