A. Pandey A. Pandey - 1 year ago 84
Java Question

Roll Die JAVA Program using Array

I have difficulty in understanding some line of code in this roll die JAVA program using arrays.
This program notes the frequency of the numbers 1-6 and then displays in console.

import java.security.SecureRandom;

public class RollDie{

public static void main(String[] args){
SecureRandom randomNumbers=new SecureRandom();
int[] frequency=new int[7]; //array of frequency counter

//roll die 6000000 times, use die value as frequency index
for(int i=1; i<=6000000;i++)

for(int face=1;face<frequency.length;face++)
System.out.printf("%4d%10d%n", face, frequency[face]);

can anyone explain this line:


Answer Source

The line is written quite unclearly. I took a long time comprehending it as well.

First, we see the ++ prefix operator. You know what it does right? It increments the variable on the left before any other operators are evaluated. Since there aren't any other operators, it just increments frequency[1+randomNumbers.nextInt(6)] by 1.

So what is this frequency[1+randomNumbers.nextInt(6)] thingy?

First, you would see that it is accessing the array frequency, since there are those [] things. So which index to access? Well, 1+randomNumbers.nextInt(6)!

nextInt(x) returns a uniformly distributed random number between 0 and x-1. nextInt(6) returns a random number between 0 and 5. But a typical dice roll always results in 1 - 6! That's why we need to add 1 to the return value of nextInt. As a result, the index will be between 1 - 6.

Thus, as a whole, this whole line just rolls the dice (1+randomNumbers.nextInt(6)), and increment the corresponding index of the array frequency.

It would probably be easier to read if it were written like this:

int diceRoll = randomNumbers.nextInt(6);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download