我需要帮助计算连续显示的连续头数。我不知道怎么能这样做。有人能告诉我这个程序最快捷,最简单的方法吗?我似乎无法弄明白,我已经考虑了一段时间。任何帮助将不胜感激。
import java.util.Scanner;
import java.util.Random;
public class test2
{
public static void main( String[] args )
{
Random randomNumber = new Random();
//declares and initializes the headCount and consecutiveHeads
int headCount = 0;
int consecutiveHeads = 0;
//Ask user how many coin flips
System.out.println( "How many coin flips?" );
//stores the input in coinFlips
Scanner input = new Scanner( System.in );
int coinFlips = input.nextInt();
//loop makes sure that program only accepts values or 1 or greater
while (coinFlips < 1)
{
System.out.println("Please enter a value greater than or equal to 1.");
coinFlips = input.nextInt();
}
for (int i = 0; i < coinFlips; i++)
{
int coinFace = randomNumber.nextInt(2);
if (1 == coinFace)
{
//Print H for heads and increment the headCount
System.out.print( "H" );
headCount++;
}
else
{
//print T for tails
System.out.print( "T" );
}
}
}
}
答案 0 :(得分:3)
我说的最简单的方法就是在if子句的Heads-side中计算连续的头,并在Tails端将其设置为零。像这样:
[...]
if (1 == coinFace)
{
//Print H for heads and increment the headCount
System.out.print( "H" );
headCount++;
consecutiveHeads++;
}
else
{
//print T for tails
System.out.print( "T" );
consecutiveHeads = 0;
// if current head count is greater than previously recorded maximum count, replace old max
}
如果您想记住最高连续计数,您可能需要为此添加变量。所以上面变成了:
if (1 == coinFace)
{
//Print H for heads and increment the headCount
System.out.print( "H" );
headCount++;
consecutiveHeads++;
if(consecutiveHeads > longestHeadStreak)
{
longestHeadStreak = consecutiveHeads;
}
}