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
解决方案
您将当前值与前一个值进行比较,如果它们不同,则发出一个空格。
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(' ');
}
}
推荐阅读
- scala - 如何将运动流转换为新流?
- json - 在 PostMan 中模拟特定的 CURL。有问题
- javascript - How to load a component from a button click in react?
- linux - Linux:当有多个逻辑卷时,文件究竟保存在哪里?
- java - 来自 Lambda 表达式的有效 void 返回语句(示例:可运行)
- bazel - 如何指定 bazel cc_binary 规则生成的预期文件扩展名?
- spring-boot - 春季启动升级后获取 java.lang.NosuchFieldError:BINARY
- azure-devops - 如何更改 Azure DevOps 环境代理文件夹结构
- linux - 在 unix 中使用 SFTP 获取文件大小和名称的干净列表
- javascript - shopify 嵌入式应用会话令牌使用烧瓶进行身份验证