添加一个空格以分隔不同的硬币翻转

时间:2018-11-18 10:38:16

标签: java

我正在编写一个程序,在其中跟踪您要执行多少次翻转,然后列出结果。

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可以存储先前的结果,然后进行比较。

Scanner scnr = new Scanner(System.in);
Random rand = new Random();

System.out.println("Welcome to the coin flip analyzer.");

System.out.print("How many flips? ");
int flips = scnr.nextInt();

String previousResult = null;
String result;
for (int i = 0; i < flips; ++i) {
    result = rand.nextInt(2) == 0 ? "H" : "T";
    System.out.print(!result.equals(previousResult) ? " " + result : result);   
    previousResult = result;
}

对于我在循环中使用的语法,可以参考Java - Ternary

样品

Welcome to the coin flip analyzer.
How many flips?  10
T H T H TT H TTT