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!
//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!