Write a program that lets the user continuously guess whethe
Write a program that lets the user continuously guess whether the flip of a coin results in heads or tails until the user wins. 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.
Here are sample runs:
Guess head or tail? Enter 0 for head and 1 for tail: 0
Sorry, it is a tail
Guess head or tail? Enter 0 for head and 1 for tail: 1
Sorry, it is a head
Guess head or tail? Enter 0 for head and 1 for tail: 1
Correct Guess!
Solution
GuessFlip.java
import java.util.Random;
import java.util.Scanner;
public class GuessFlip {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random r = new Random();
while(true){
int toss = r.nextInt(2);
System.out.print(\"Guess head or tail? Enter 0 for head and 1 for tail: \");
int guess = scan.nextInt();
if(guess == toss){
System.out.println(\"Correct Guess!\");
break;
}
else{
if(toss == 0){
System.out.println(\"Sorry, it is a tail\");
}
else{
System.out.println(\"Sorry, it is a head\");
}
}
}
}
}
Output:
Guess head or tail? Enter 0 for head and 1 for tail: 0
Sorry, it is a head
Guess head or tail? Enter 0 for head and 1 for tail: 1
Sorry, it is a tail
Guess head or tail? Enter 0 for head and 1 for tail: 1
Sorry, it is a tail
Guess head or tail? Enter 0 for head and 1 for tail: 1
Correct Guess!

