0

我需要帮助计算连续出现的正面数量。我不确定我该怎么做。谁能告诉我为这个程序做最快和最简单的方法吗?我似乎无法弄清楚,我已经考虑了一段时间。任何帮助,将不胜感激。

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" );


                }
            }


    }
}
4

1 回答 1

3

我想说的最简单的方法就是在 if 子句的 Heads 侧计算连续的头,并在 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;
     }
 }
于 2013-04-13T05:56:38.100 回答