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);
}
}
}