连续三个Java程序?

时间:2016-12-08 23:45:54

标签: java eclipse coin-flipping

在JAVA中编写一个程序,该程序将模拟投掷硬币并输出连续获得三个“头”所需的投掷次数。该程序还将向模板输出模拟折腾的“头部”和“尾部”。例如,您的程序可能会产生如下输出:

  • 实施例1:HTHHH
  • 5
  • 实施例2:TTTHTHHTTTHHH
  • 14

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

我的代码:

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

    }
}

1 个答案:

答案 0 :(得分: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");
    }
}