2016-11-09 34 views
-5

不知道該怎麼辦,以及它是否在我的if語句或我做了一個新的。 只能獲得最長的頭部運行時間。必須得到最長的運行硬幣翻轉

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

    public void run() 
    { 
      int headFlips = 0; 
      int tailFlips = 0; 
      int longestRun = 0; 
      int max = 0; 
     for (int i = 0; i < FLIPS; i++) 
     { 
     if(Randomizer.nextBoolean()) 
     { 
      System.out.println("Heads"); 
      headFlips++; 
     } 
     else 
     { 
     System.out.println("Tails"); 
     tailFlips++; 
     } 
     if() 
     { 
      longestRun++; 
      if(max < longestRun) 
      { 
       max = longestRun; 
      } 

     } 
     else 
     { 
      longestRun = 0; 
     } 


     }//end for loop 
     System.out.println("Longest streak of heads: " +longestRun); 
    } 
} 

PLEASE HELP ME !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

+0

凡'Randomizer'定義? –

+1

你的「!」關鍵是卡住... – Robert

回答

1

考慮這個簡單的邏輯

longestRun = 0; 
    currentRun = 0; 
    for (int i = 0; i < FLIPS; i++) 
    { 
    if(Randomizer.nextBoolean()) 
    { 
     System.out.println("Heads"); 
     // headFlips++; - not used 
     currentRun ++; 
    } 
    else 
    { 
     System.out.println("Tails"); 
     // tailFlips++; - not used 
     longestRun = Math.max (longestRun, currentRun); 
     currentRun = 0; 
    } 
    } 

    // need to do after the loop too 
    longestRun = Math.max (longestRun, currentRun); 
    System.out.println("Longest streak of heads: " +longestRun); 
+0

你比我的優雅一些;)但不知道什麼'Randomizer'是或來自雖然。 – BlackHatSamurai

+0

我會認爲它是一個類型的對象https://docs.oracle.com/javase/7/docs/api/java/util/Random.html –

+0

您好Downvoter先生 - 有何評論? –

-1

你可以做這樣的事情:

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

    public void run() 
    { 
      int longestRun = 0; 
      int max = 0; 

     Random r = new Random(); 
     for (int i = 0; i < FLIPS; i++) 
     { 

     if(r.nextBoolean()) 
     { 
      System.out.println("Heads"); 
      //increment max 
      max++; 
     } 
     else 
     { 
      System.out.println("Tails"); 
      //since the run is broken, compare the max & the longest run. 
      //if max is greater, then set longest run to max 
      if(max > longestRun) 
       { 
        longestRun = max; 
       } 
       //reset your counter 
       max = 0; 
     } 



     }//end for loop 

     //need to compare last run of flipping in case you end on heads 
     if(max > longestRun) 
     { 
     longestRun = max; 
     } 
     System.out.println("Longest streak of heads: " +longestRun); 
    } 
}