Java program that lets the user guess whether the flip of a coin results in heads or tails. The program randomly generates an integer 0 or 1, which represents head or tail. The program prompts the user to enter a guess and reports whether the guess is correct or incorrect.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.Scanner; public class HeadsOrTail { public static void main (String [] args) { int number, guess; // Obtain the random number 0 or 1 number = (int) (Math.random() * 2); // Prompt the user to enter a guess Scanner input = new Scanner(System.in); System.out.print("Guess head or tail? Enter 0 for head and 1 for tail: "); guess = input.nextInt(); // Check the guess if (guess == number) { System.out.println("Correct guess"); } else { System.out.println("Wrong guess"); } } } |