gpt4 book ai didi

java - 添加空格来分隔不同的抛硬币 Action

转载 作者:行者123 更新时间:2023-12-02 10:35:00 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于java - 添加空格来分隔不同的抛硬币 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53359938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com