2017-03-21 53 views
0

我一直堅持這個星期,我不知道如何做到這一點。我只想要最長的頭。我嘗試了無數次,我只是不知道自己做錯了什麼。計數最長的頭

public class LongestStreak extends ConsoleProgram 
{ 
public static final int FLIPS = 100; 
int currentRun; 
int runStart; 
int maxRun; 

public void run() 
{ 
double heads = 0; 
double tails = 0; 
    for(int i = 0; i < FLIPS; i++) 
     { 
     if(Randomizer.nextBoolean()) 
     { 
      System.out.println("Heads"); 
      heads++; 
      currentRun++; // use ++ in preference to +=1, and this should be before maxRun test 
      if (maxRun < currentRun) { 
       maxRun = currentRun; 
       runStart = currentRun - i; // this will produce a 1-based position 
      } else { 
      currentRun = 0; 
      } 
     } 
     else 
     { 
      System.out.println("Tails"); 
      tails++; 
     } 
    } 
    System.out.println(FLIPS); 
} 

}

+1

你從不打印連勝。而是打印出循環的邊界。 –

+1

當尾部翻轉時,您應該考慮將currentRun重置爲0。 – Compass

+0

啊,所以我改變它打印出maxRun,但maxRun似乎只是所有的頭。在100次翻轉中,有51個頭。我不想那樣。 –

回答

0

我不知道如果我明白你的問題所在,但在這裏我有一個解決方案,這將打印您的100中的最長連勝FLIPS

public static void run() { 
    Random r = new Random(); 
    double heads = 0; 
    double tails = 0; 
    for (int i = 0; i < FLIPS; i++) { 
     if (r.nextBoolean()) { 
      System.out.println("Heads"); 
      heads++; 
      currentRun++; 
      if (maxRun < currentRun) { 
       maxRun = currentRun; 
       runStart = currentRun - i; 
      } 
     } else { 
      System.out.println("Tails"); 
      tails++; 
      currentRun = 0; 
     } 
    } 
    System.out.println(FLIPS); 
    System.out.println(maxRun); 
} 
+0

我補充說,但它不起作用 –

+0

任何人都知道該怎麼辦? –

+0

@AZGames什麼不工作? – XtremeBaumer

0
public class LongestStreak extends ConsoleProgram 
{ 
    public static final int FLIPS = 100; 


    public void run() 
    { 

     int consecutiveHeads = 0; 
     int maxRun = 0; 

     for(int i = 0; i < FLIPS; i++) 
     { 
      if(Randomizer.nextBoolean()) 
      { 
       System.out.println("Heads"); 
       consecutiveHeads++; 
        if(maxRun < consecutiveHeads) 
        { 
         maxRun = consecutiveHeads; 
        } 


      } 
      else 
      { 
       System.out.println("Tails"); 
       consecutiveHeads = 0; 
      } 
     } 

         System.out.println("Longest streak of heads: " + maxRun); 
    } 
} 
+1

請解釋此代碼如何解決問題。 –