SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:11 | ISBN:9780136091813 | Edition: 2

Question

Write a method called threeHeads that repeatedly flips a coin until the results of the coin toss are three heads in a row. You should use a Random object to make it equally likely that a head or a tail will appear. Each time the coin is flipped, display H for heads or T for tails. When three heads in a row are flipped, the method should print a congratulatory message. Here is a possible output of a call to the method:
T T H T T T H T H T H H H
Three heads in a row!

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

//package indefinite_loops;

import java.util.Random;

public class ThreeHeads {

    public void threeHeads() {
        
        // set heads count to zero initially
        int numOfHeads = 0;
        // initiate Random Object
        Random random = new Random();
        
        // continue the loop as long as heads count eqsuls 3
        while (numOfHeads < 3) {
            
            // gives random boolean value
            boolean head = random.nextBoolean();
            
            if (head) {
                System.out.print("H ");
                // if it heads increment the count
                numOfHeads++;
            } else {
                System.out.print("T ");
                numOfHeads = 0;
            }
        }
        System.out.println("\nThree heads in a row!");
    }

    public static void main(String[] args) {
        
        // call the method
        ThreeHeads th = new ThreeHeads();
        th.threeHeads();

    }

}
Output:

H T H H T H T H T T T T H H T T T T T T T H T T T H T H T H H T T T T T H H T H H H 
Three heads in a row!

 

0 0

Discussions

Post the discussion to improve the above solution.