java - 具有多个打印问题的硬币翻转程序

标签 java printing while-loop

我刚刚开始学习 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(); 从您的scan.nextInt() 调用中读取新行。您可以在这里阅读更多信息Scanner is skipping nextLine() after using next() or nextFoo()?

最好在每次调用 .nextInt() 之后调用 .nextLine() 以始终使用换行符。

关于java - 具有多个打印问题的硬币翻转程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923392/

相关文章:

python-2.7 - 在字典中打印多个 YAML 列表

java - 搜索用于将 GUI 组件写入 PDF 的 Java 库或第 3 方库

C编程: A Simple Countdown Program

java - 递归函数和非递归函数返回不同的结果

java - 将 hibernate 与 Restful Web 服务集成时出现问题?

java虚拟机启动器错误: unable to access jarfile

java - xstream - 无法初始化自定义列表元素的值

java - 如何最高效的获取完整的URL地址?

Android:连接并打印到 Bixolon SPP-R200

Javascript ' Array ' 和 ' Loop ' "variable[i] "如何成为条件