forked from angiejones/java-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoinTossGame.java
More file actions
61 lines (47 loc) · 1.72 KB
/
Copy pathCoinTossGame.java
File metadata and controls
61 lines (47 loc) · 1.72 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
package exercises.project;
import java.util.Scanner;
public class CoinTossGame {
private Scanner scanner;
public static void main(String[] args){
CoinTossGame game = new CoinTossGame();
game.scanner = new Scanner(System.in);
Player player1 = new Player(game.askPlayerName());
player1.setGuess(game.askGuess());
Player player2 = new Player(game.askPlayerName());
if(player1.getGuess().equalsIgnoreCase(Coin.HEADS)){
player2.setGuess(Coin.TAILS);
}else{
player2.setGuess(Coin.HEADS);
}
System.out.println("Flipping the coin...");
Coin coin = new Coin();
coin.flip();
System.out.println("The coin landed on " + coin.getSide());
game.determineWinner(player1, player2, coin);
game.scanner.close();
}
private String askPlayerName(){
System.out.println("Enter the player's name:");
return scanner.nextLine();
}
private String askGuess(){
String prompt = String.format("%s or %s?", Coin.HEADS, Coin.TAILS);
System.out.println(prompt);
String guess = scanner.nextLine();
while(!guess.equalsIgnoreCase(Coin.HEADS)
&& !guess.equalsIgnoreCase(Coin.TAILS)){
System.out.println("Invalid guess. Try again. " + prompt);
guess = scanner.nextLine();
}
return guess;
}
private void determineWinner(Player player1, Player player2, Coin coin){
String winner;
if(coin.getSide().equalsIgnoreCase(player1.getGuess())){
winner = player1.getName();
}else{
winner = player2.getName();
}
System.out.println("The winner is " + winner);
}
}