2012-03-20 62 views
0

作業。骰子游戲。我有一個數組,代表五個骰子。考慮: diceRoll[] = {6,3,3,4,5}。我想創建一個具有價值的計數一到六個包含在diceRoll[]第二陣列(例如,occurence[] = {0,0,2,1,1,1}以上的diceRoll[])。但我擔心我在嵌套循環迷路並且似乎無法人物我應該返回哪個價值。 occurence[]是一個全局變量,其意圖是該數組將包含六個值...(在索引[0]),二進制數(在[1]),三(在[2])的計數等。計算數組中值的實例

到目前爲止:

for(i=1;i<7;i++) /* die values 1 - 6 
    { 
     for(j=0;j<diceRoll.length;j++) /* number of dice 
     { 
      if (diceRoll[j] == i) /* increment occurences when die[j] equals 1, then 2, etc. 
      occurence = occurence + 1; 
     } 
    } 
    return occurence; 
    } 

我不能,然而,得到的發生= occurence + 1工作。 bad operand types for binary operator是我最常見的錯誤。我懷疑我需要增加occurence其中一個或兩個for循環,但我迷路了。

指導?或者也許是單線簡單的方法來做到這一點? d

+0

你聽說++的?使您的代碼看起來更加專業。 – parion 2012-03-20 00:30:50

+0

'爲(I = 0; I <6;我++)/ *模具值1 - 6 { \t occurence [diceRoll [I]] ++; – nullpotent 2012-03-20 00:31:53

回答

4

最簡單的方法是創建第二個數組,以便 發生[0] = 1發生的次數[1] = 2的次數等等。然後這變成1循環方法。

//method to return number of occurrences of the numbers in diceRolls 
int[] countOccurrences(int[] diceRolls) { 
    int occurrence[] = new int[6]; //to hold the counts 

    for(int i = 0; i < diceRolls.length; i++) { //Loop over the dice rolls array 
     int value = diceRolls[i]; //Get the value of the next roll 
     occurence[value]++; //Increment the value in the count array this is equivalent to occurrence[value] = occurrence[value] + 1; 
     //occurrence[diceRolls[i]]++; I broke this into two lines for explanation purposes 
    } 

    return occurrence; //return the counts 
} 

編輯:

然後得到計數針對任何特定值使用occurrence[value-1]

+0

謝謝,我有點困惑,我會插入這個...... {在第一行的結尾是把我扔掉。這應該是一個新的方法,我會通過我的骰子數組?在哪裏發生增量...或者這個代碼是否只是在diceRolls中統計不同的值,因爲它循環遍歷所有五個值?我是新的...我很容易混淆。 :) – dwwilson66 2012-03-20 00:53:59

+0

我寫這個作爲一種方法,你會傳遞你的骰子數組。所以你可以稱它爲'int occurrence [] = new int [6]; occurrence = countOccurrences(diceRolls);'但你也可以多次使用它。如果你只需要計算一次,你只需要循環,它會代替你的代碼片段。我會在代碼中添加註釋以向您展示它的功能。 – twain249 2012-03-20 00:57:54

+0

很清楚。我現在玩代碼。非常感謝你!這開始凝結在我的大腦中。 – dwwilson66 2012-03-20 01:06:36