如何在java硬币翻转程序中计算和分离连续的正面或反面翻转



我正试图在一个简单的java掷硬币程序中的连续运行之间添加空格和计数器。

我想要这个输出:

打印如下:HHHH4 T1 H1 TTTTT 7 H1 TTT3 HHH3 TTTT4 H1 TT2 HHH3 TTP4 HH2 T1 HHHHH 5 TTTTTT 6 H1 T1

我不知道如何在循环中定位条件,以便在连续的"T"one_answers"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");
}
}

通过单一方法:

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();
if (timesFlipped <= 0)
return;
Random randomNum = new Random();
boolean isHeads = false;
int sequence = 0;
for (int i = 0; i < timesFlipped; i++) {
boolean prevFlip = isHeads;
isHeads = randomNum.nextBoolean();
if (i > 0 && isHeads != prevFlip) {
System.out.print(sequence + " ");
sequence = 0;
}
sequence++;
System.out.print(isHeads ? "H" : "T");
}
System.out.println(sequence);
}

最新更新