What is the correct way to prompt a user for input in Java, and how can I handle both strings and numbers effectively?

Let’s take it one step further and make sure the user can only enter “heads” or “tails”:

import java.util.Scanner;

public class CoinFlipGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String userChoice;

        do {
            System.out.println("Enter heads or tails:");
            userChoice = scanner.nextLine().trim().toLowerCase();
        } while (!userChoice.equals("heads") && !userChoice.equals("tails"));

        int bob = (int) (Math.random() * 2);
        String computerChoice = (bob == 0) ? "heads" : "tails";

        System.out.println("Computer flipped " + computerChoice);

        if (userChoice.equals(computerChoice)) {
            System.out.println("You win!");
        } else {
            System.out.println("Sorry, you lost!");
        }

        scanner.close();
    }
}

This keeps your program from breaking if someone types something random like “coin” or “123”.