Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that lets the user continuously guess whether the flip of a coin

ID: 3930311 • Letter: W

Question

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!

Explanation / Answer

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!

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote