Repository navigation
Expand file tree
/
Copy pathLesson37_rockPaperScissors.java
More file actions
63 lines (54 loc) · 2.31 KB
/
Copy pathLesson37_rockPaperScissors.java
File metadata and controls
63 lines (54 loc) · 2.31 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
53
54
55
56
57
58
59
60
61
62
63
import java.util.Scanner;
import java.util.Random;
public class Lesson37_rockPaperScissors {
static Scanner sc = new Scanner(System.in);
static Random random = new Random();
static final String[] CHOICES = {"rock", "paper", "scissors"}; // game state
public static void main(String[] args) {
String playAgain = "yes";
do {
String playerChoice = getPlayerChoice();
String computerChoice = CHOICES[random.nextInt(3)];
displayWinner(playerChoice, computerChoice);
System.out.print("Do you want to play again?: ");
playAgain = sc.nextLine().toLowerCase();
System.out.println();
} while(playAgain.equals("yes"));
System.out.println("Thank you for playing!");
sc.close();
}
static String getPlayerChoice() {
System.out.println("Welcome to Rock, Paper, Scissors!");
System.out.println("Ready?");
System.out.println("ROCK!\n" +
"PAPER!\n" +
"SCISSORS!\n" +
"SHOOT!\n");
System.out.print("Rock, Paper, or Scissors?: ");
String playerChoice = sc.nextLine().toLowerCase();
while(!playerChoice.equals("rock") &&
!playerChoice.equals("paper") &&
!playerChoice.equals("scissors")) {
System.out.println("Choose an appropriate response!");
System.out.println("ROCK!\n" +
"PAPER!\n" +
"SCISSORS!\n" +
"SHOOT!\n");
System.out.print("Rock, Paper, or Scissors?: ");
playerChoice = sc.nextLine().toLowerCase();
}
return playerChoice;
}
static void displayWinner(String playerChoice, String computerChoice) {
System.out.println("The computer has chosen: " + computerChoice + "!");
if(playerChoice.equals(computerChoice)) {
System.out.println("YOU TIED!");
return;
}
switch(playerChoice) {
case "rock" -> System.out.println(computerChoice.equals("scissors") ? "YOU WIN!" : "YOU LOSE!");
case "paper" -> System.out.println(computerChoice.equals("rock") ? "YOU WIN!" : "YOU LOSE!");
case "scissors" -> System.out.println(computerChoice.equals("paper") ? "YOU WIN!" : "YOU LOSE!");
}
}
}