java - 如何在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;
}
}
}
解决方案
你可以只存储最后一次翻转和一个计数器
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");
}
}
推荐阅读
- flutter - 在颤振中通过webview在canva中登录谷歌的问题
- haskell - ekg-core/GHC RTS:在 Google Cloud Run 上运行时的虚假 GC 统计信息
- c - 为什么我的程序会泄漏 12 字节的内存,未初始化的值从何而来?
- python - 如何使用 python 选择 JSON 文件的某些部分?
- python-3.x - 如何使用列值在熊猫数据框中创建新列?
- php - Laravel:如何解决“SQLSTATE [HY000]:一般错误:1215 无法添加外键约束”
- node.js - 如何在 Dialogflow 实现内联中使用多次网络抓取?以及如何在履行内联代码中检测错误?
- javascript - 如何在 React js 中从 firebase 实时数据库中获取数据
- android - 如何在片段内的函数中传递imageButton和drawable文件
- c++ - 确定当前是否正在过滤文件夹视图