How to Write a Coin Toss Game in Java
Check out the following source code for a simple coin toss game written in Java. This game program illustrates the use of Random class and enumerators in Java. The program asks the user to guess the coin toss and then compares the value with the actual coin toss result. Coin toss program runs the game in an infinite loop until the user decides to quit by entering q.
import java.util.Random; import java.util.Scanner; // Coin toss/flip game in Java public class CoinTossGame { private enum Coin { Head, Tail }; public static void main(String[] args) { CoinTossGame game = new CoinTossGame(); game.startGame(); } // Starts a coin flip game till user decides to quit. private void startGame() { Scanner scanner = new Scanner(System.in); Coin guess; while (true) { System.out.print("Enter you guess (h for heads, t for tails, q to quit):"); String choice = scanner.nextLine(); if (choice.equalsIgnoreCase("q")) { break; } else if (choice.equalsIgnoreCase("h")) { guess = Coin.Head; } else if (choice.equalsIgnoreCase("t")) { guess = Coin.Tail; } else { System.out.println("Wrong choice! Try again!"); continue; } Coin toss = tossCoin(); if (guess == toss) { System.out.println("Congratulations! You won the toss!"); } else { System.out.println("Sorry! You lost the toss."); } } scanner.close(); } // Flip a coin and return result private Coin tossCoin() { Random r = new Random(); int i = r.nextInt(2); if (i == 0) { return Coin.Head; } else { return Coin.Tail; } } }
Here is a coin toss game in action!
$ java CoinTossGame Enter you guess (h for heads, t for tails, q to quit):h Congratulations! You won the toss! Enter you guess (h for heads, t for tails, q to quit):t Congratulations! You won the toss! Enter you guess (h for heads, t for tails, q to quit):t Congratulations! You won the toss! Enter you guess (h for heads, t for tails, q to quit):h Congratulations! You won the toss! Enter you guess (h for heads, t for tails, q to quit):t Congratulations! You won the toss! Enter you guess (h for heads, t for tails, q to quit):h Sorry! You lost the toss. Enter you guess (h for heads, t for tails, q to quit):h Sorry! You lost the toss. Enter you guess (h for heads, t for tails, q to quit):t Congratulations! You won the toss! Enter you guess (h for heads, t for tails, q to quit):q $