我有一個數組,用於計算從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語句?
你知道,那個switch語句是完全沒有必要的。 – 2014-10-05 13:58:17