我有一个数组,用于计算从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