带有多个打印问题的硬币翻转程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带有多个打印问题的硬币翻转程序相关的知识,希望对你有一定的参考价值。

我刚刚开始使用Java,这是我最近编写的硬币翻转程序。因此,应该产生满足用户设置要求的硬币翻转序列,但是到结束时,它应该询问用户是否要再次走。我遇到一个问题,当问题结束时它将两次打印问题。我真的需要弄清楚这一点,以便对我的代码提出任何建议/澄清。

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    outer: while (true) {
        System.out.print("Ready to run a coin flip simulation. Enter the number of sequences: ");
        int sequences = scan.nextInt();

        System.out.print("How many heads should each sequence have? ");
        int heads = scan.nextInt();

        System.out.print("How many tails should each sequence have? ");
        int tails = scan.nextInt();

        System.out.println("Simulating Sequences");

        int tFlips = 0;
        int mFlips = 0;

        for (int i = 1; i <= sequences; i++) {
            int h = 0;
            int t = 0;
            String s = "";
            while (t < tails || h < heads) {
                if (Math.random() < 0.5) {
                    h++;
                    s += "H";
                } else {
                    t++;
                    s += "T";
                }
                tFlips++;
            }

            if (t + h > mFlips) {
                mFlips = t + h;
            }

            System.out.println(i + " - " + s);
            h = 0;
            t = 0;
            s = "";

        }
        System.out.printf("The average number of flips was " + ((float) tFlips / sequences) + " and maximum was %d", mFlips);

        System.out.println("\r\n");

        boolean go = true;

        while (go) {
            System.out.print("Would you like to run another simulation? (y/n): ");
            String c = scan.nextLine();

            if (c.equalsIgnoreCase("y")) {
                break;
            } else if (c.equalsIgnoreCase("n")) {
                break outer;
            } else {
                continue;
            }
        }
        System.out.print("\r\n");
    }
}
答案

String c = scan.nextLine();更改为String c = scan.next();。而且您实际上并不需要while(go)循环,如果执行此操作则更简单:

另一答案

您的String c = scan.nextLine();从您的scan.nextInt()呼叫中读取新行。您可以在这里阅读更多内容Scanner is skipping nextLine() after using next() or nextFoo()?

以上是关于带有多个打印问题的硬币翻转程序的主要内容,如果未能解决你的问题,请参考以下文章

硬币翻转指令

P1146 硬币翻转

如何模拟有偏硬币的翻转?

luogu P1146 硬币翻转

洛谷——P2708 硬币翻转

P1146 硬币翻转