-1

用 JAVA 编写一个程序,该程序将模拟掷硬币并输出连续获得三个“正面”所需的掷硬币次数。该程序还将模拟抛掷的“正面”和“反面”输出到屏幕上。例如,您的程序可能会产生如下输出:

  • 示例 1:HTHHH
  • 5
  • 示例 2:TTTHTHHTTTTHHH
  • 14

现在当我运行它时,它会连续打印 H 并且运行无限次。它也没有翻转尾巴,只有头。所以有人可以帮我修复我的代码请.....谢谢。

我的代码:

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

    }
}
4

1 回答 1

1

试试这段代码,看看它是否达到了你想要的效果

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");
    }
}
于 2016-12-09T00:24:44.680 回答