I have an array that counts how many times each value from 1 to 6 appears in a dice simulator which "rolls a dice" 100 times. My goal is to find the most frequent dice roll.
This is my code so far, and everything works fine except the for-loop in the end which only outputs "6".
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);
Any idea about what I'm doing wrong? I'm trying to keep the code short and easy. I'm in my first semester learning java so an unadvanced solution would be preferable.
Also, is it possible to count the frequency of each diceThrow without using a switch/if statement?