Search code examples
javaeclipsecoin-flipping

Three Heads in a row Java Program?


Write a program in JAVA that will simulate coin tosses and output the number of tosses required to get three “heads” in a row. This program will also output to the screen the “heads” and “tails” that it has simulated tossing. For example, your program may produce output as follows:

  • Example 1: HTHHH
  • 5
  • Example 2: TTTHTHHTTTTHHH
  • 14

Now when I run it, it continuous prints H and it runs infinite times. Its not flipping Tails either,only heads. So can someone help me fix my code Please.....Thank you.

My Code:

    import java.util.*;

public class threeHeads {

    public static void main(String[] args) {

        boolean first = false;
        boolean second = false;
        int count = 0;

        Random random = new Random();

          while(true){

                int n = random.nextInt(2) + 1; //1 is Heads, 2 is Tails 

                if (n == 1){
                    System.out.println("H");  
                    count++;

                if (first == false){
                    first = true;
                } else if (second == false){
                    second = true;
                } else if (second == true){
                    break;
                } 
                }
                else {
                    System.out.println("T");
                    first = false;
                    second = false;
                    count++;
                  } 

            }

          if (count == 3){
                System.out.println(count);
            }

    }
}

Solution

  • give this code a try to see if it achieves what you want

    public class flipper {
        public static void main(String[] args) {
            int heads = 0;
            int count = 0;
            while (heads < 3) {
                int flip = (int)(Math.random() * 2);  // range [0, 1]
                count++;
                if (flip == 0) {
                    System.out.print("H");
                    heads++;
                } else {
                    System.out.print("T");
                    heads = 0;
                }
            }
            System.out.println("\nIt took " + count + " flips to achieve three heads in a row");
        }
    }