Reputation: 47
I am writing a dice roll program. The code works fine in working out the face and number of frequencies. How I can calculate the percentage for the frequency of each face?
import java.util.Random;
public class Dice{
public static void main (String[] args){
Random random = new Random(); // Generates random numbers
int[] array = new int[ 7 ]; // Declares the array
//Roll the die 10000 times
for ( int roll = 1; roll <=10000; roll++ ) {
/*++array[1 + random.nextInt(6)];*/
int dice = 1 + random.nextInt(6);
++array[dice];
}
System.out.printf("%s%10s\n", "Face", "Frequency");
// outputs array values
for (int face = 1; face < array.length; face++) {
System.out.printf("%4d%10d\n", face, array[face]);
}
}
}
Upvotes: 1
Views: 925
Reputation: 137064
The frequency is just the count of each face divided by the total count.
for (int face = 1; face < array.length; face++) {
System.out.printf("%4d%10f\n", face, array[face] / 10000.0);
}
The division must be performed with a double value (otherwise, an integer division would be performed and the result would always be 0), explaining why I divided with 10000.0
and not 10000
.
I also changed the String format from %10d
to %10f
because you want to print a decimal number, not an integer. See the Formatter
Javadoc for the list of all token.
Also, I suggest you make a local variable holding the total count so as not to repeat it twice.
Upvotes: 2