2013-04-13 61 views
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"); 


       } 
      } 


    } 
} 

回答

3

我想說的最簡單的方法就是在if子句的頭端計算連續的頭並在尾端將其設置爲零。像這樣:

[...] 
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; 
    } 
} 
+0

我不確定那是如何工作的。如果我在If子句中增加連續的頭部,那麼它是否與headCount基本相同? – user1793565

+0

不,因爲您在獲得Tails後立即將連續的頭設置爲零。您不會將headCount設置爲零,只需將其增加即可。看一下else子句。 – jelgh

+0

我會初始化longestHeadStreak = 1或0嗎? – user1793565