首页 > 解决方案 > 如何在java掷硬币程序中计算和分离连续的正面或反面翻转?

问题描述

我正在尝试在一个简单的 java 掷硬币程序中的连续运行之间添加空格和计数器。

我想要这个输出:

看起来像这样打印:HHHH4 T1 H1 TTTTTTT7 H1 TTT3 HHH3 TTTT4 H1 TT2 HHH3 TTTT4 HH2 T1 HHHHH5 TTTTTT6 H1 T1

我不确定如何在循环中定位条件,以便在连续的“T”和“H”之间打印空格和计数器。我需要使用不同类型的循环吗?我尝试重新排列循环并使用 break; 并继续;但没有得到正确打印的结果。

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    System.out.print("How many times do you want to flip the coin? ");
    int timesFlipped = scnr.nextInt();
    Random randomNum = new Random();


    for (int i=0; i < timesFlipped; i++) {
        int currentflip = randomNum.nextInt(2);
        int previousFlip = 0;
        int tailsCount = 0;
        int headsCount = 0;

        if (currentflip == 0) {
            System.out.print("H");
            previousFlip = 0;
            headsCount++;
        }
        else if (currentflip == 1) {
            System.out.print("T");
            previousFlip = 1;
            tailsCount++;
        }

        if (previousFlip == 0 && currentflip == 1) {
            System.out.print(headsCount + " ");
            headsCount = 0;
        }
        else if (previousFlip == 1 && currentflip == 0) {
            System.out.print(tailsCount + " ");
            tailsCount = 0;
        }

    }


}

标签: javaloops

解决方案


你可以只存储最后一次翻转和一个计数器

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    System.out.print("How many times do you want to flip the coin? ");
    int timesFlipped = scnr.nextInt();
    Random randomNum = new Random();

    int counter = 1;
    int previousFlip = randomNum.nextInt(2);
    printFlip(previousFlip);
    for (int i=1; i < timesFlipped; i++) {
        int currentflip = randomNum.nextInt(2);
        if (currentflip == previousFlip) {
            counter++;
        } else {
            System.out.print(counter + " ");
            counter = 1;
            previousFlip = currentflip;
        }

        printFlip(currentflip);
    }
    System.out.print(counter);

}

private static void printFlip(int currentflip) {
    if (currentflip == 0) {
        System.out.print("H");
    }
    else if (currentflip == 1) {
        System.out.print("T");
    }
}

推荐阅读