2014-10-05 70 views
0

我有一個數組,用於計算從1到6的每個值出現在擲骰子100次的骰子模擬器中的次數。我的目標是找到最頻繁的擲骰子。Java - 檢查給定索引處的數組是否包含給定的int

這是我的代碼到目前爲止,除了最後只輸出「6」的for-loop外,一切都正常。

Random dice = new Random(); 

    int diceThrow[] = new int[100]; 
    int throwsPerDice[] = new int[6];  

    for(int i = 0; i < 100; i++){ 
     diceThrow[i] = dice.nextInt(6) + 1; 

     switch (diceThrow[i]){ 
      case 1: 
       throwsPerDice[0]++; 
       break; 
      case 2: 
       throwsPerDice[1]++; 
       break; 
      case 3: 
       throwsPerDice[2]++; 
       break; 
      case 4: 
       throwsPerDice[3]++; 
       break; 
      case 5: 
       throwsPerDice[4]++; 
       break; 
      case 6: 
       throwsPerDice[5]++; 
       break; 
      default: 
       System.out.println("error"); 
     } 

    } 

    Arrays.sort(throwsPerDice); 
    int max = throwsPerDice[throwsPerDice.length-1]; 
    int mostFrequent = 0; 

    //Only outputs "mostFrequent = 6;" Why? 
    for(int i = 0; i < throwsPerDice.length; i++){ 
     if(max == throwsPerDice[i]){ 
      mostFrequent = i+1; 
     } 
    } 

    System.out.println("Most frequent dice roll : " + mostFrequent); 

有關我在做什麼錯的任何想法?我試圖保持代碼簡短。我在第一學期學習java,所以一個不太先進的解決方案會更好。

此外,是否有可能計算每個diceThrow的頻率而不使用開關/ if語句?

+2

你知道,那個switch語句是完全沒有必要的。 – 2014-10-05 13:58:17

回答

0

比方說,你的數組包含

[10, 20, 30, 20, 5, 15] 
第一循環之後

現在代碼排序的數組,所以它成爲

[5, 10, 15, 20, 20, 30] 

而且max與數組中的最後一個值初始化:30

現在最後循環迭代找到的索引包含最大元素的數組。當然,它總是最後一個,因爲你只是對數組排序。

重新思考你的算法:不要對數組排序,而是遍歷數組以找到最大元素及其索引。

只是注意:你的大switch語句應該

throwsPerDice[diceThrow[i] - 1]++; 
+0

謝謝!我現在正在工作:-) – Ferdinand 2014-10-05 14:33:19

1

主要的問題是,一旦你排序throwsPerDice,你不再知道哪個計數指的是哪個死亡。無論你事後做了什麼,你都無法恢復這些信息。

您的代碼總是返回6,因爲最高的計數已排序到throwsPerDice的最終位置。

+0

啊,我明白了!我沒有注意到這一點。謝謝! – Ferdinand 2014-10-05 14:26:56

0

被替換刪除您的這部分代碼:

Arrays.sort(throwsPerDice); 
int max = throwsPerDice[throwsPerDice.length-1]; 
int mostFrequent = 0; 

//Only outputs "mostFrequent = 6;" Why? 
for(int i = 0; i < throwsPerDice.length; i++){ 
    if(max == throwsPerDice[i]){ 
     mostFrequent = i+1; 
    } 
} 

和替換這樣的:

int mostFrequent = 0; 
for(int i = 0; i < throwsPerDice.length; i++){ 
    if(throwsPerDice[i] > throwsPerDice[mostFrequent]){ 
     mostFrequent = i; 
    } 
} 
System.out.println("Most frequent dice roll : " + mostFrequent + 1); 

這將工作。你的代碼不起作用,因爲你在使用時沒有跟蹤你的骰子:Arrays.sort

相關問題