首页 > 解决方案 > 添加一个空间来分隔不同的硬币翻转运行

问题描述

我正在编写一个程序,它会跟踪您想要执行的翻转次数,然后列出结果。

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    Random rand = new Random();
    int flips;
    int coin;
    int i;
    String result;

    System.out.println("Welcome to the coin flip analyzer.");
    System.out.print("How many flips? ");

    flips = scnr.nextInt();

    for (i = 0; i < flips; ++i) {
        coin = rand.nextInt(2);
        if (coin == 0) {
            result = ("H");
            System.out.print(result);
        }
        else {
            result = ("T");
            System.out.print(result);
        }   
    }
}

例如,对于 10 次翻转:

Welcome to the coin flip analyzer.

How many flips? 10

HHTHTHHHTT

我试图在我的代码中更改的是在硬币运行结束时添加一个空格。例如,上面的结果看起来像:

HH T H T HHH TT

标签: java

解决方案


您将当前值与前一个值进行比较,如果它们不同,则发出一个空格。

String result = null;

System.out.println("Welcome to the coin flip analyzer.");
System.out.print("How many flips? ");

flips = scnr.nextInt();

for (i = 0; i < flips; ++i) {
    String oldResult = result;
    coin = rand.nextInt(2);
    if (coin == 0) {
        result = "H";
    } else {
        result = "T";
    }   
    System.out.print(result);
    if (oldResult != null && !oldResult.equals(result)) {
        System.out.print(' ');
    }
}

推荐阅读