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

Write a method named threeHeads that repeatedly flips a coin until three heads i

ID: 660780 • Letter: W

Question

Write a method named threeHeads that repeatedly flips a coin until three heads in a row are seen. You should use a Random object to give an equal chance to a head or a tail appearing. Each time the coin is flipped, what is seen is displayed (H for heads, T for tails). When 3 heads in a row are flipped a congratulatory message is printed. Here are possible outputs of two calls to threeHeads:

(Because this problem uses random numbers, our test cases check only the general format of your output. You must still examine the output yourself to make sure the answer is correct.)

Method problem: For this problem, you are supposed to write a Java method as described. You should notwrite a complete Java class; just write the method(s) described in the problem statement.

Explanation / Answer

public static void threeHeads() {
   Random rand = new Random();
   int heads = 0;
   while (heads < 3) {
      int flip = rand.nextInt(2); // flip coin
      if (flip == 0) {             // heads
         heads++;
         System.out.print("H ");
      } else {                     // tails
         heads = 0;
         System.out.print("T ");
      }
   }
   System.out.println();
   System.out.println("Three heads in a row!");
}

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