Issue
I'm studying this code.
import java.util.*;
public class JavaRandomMath {
public static void main (String [] args)
{
Random rand = new Random();
int freq[] = new int [5];
for (int roll = 0; roll <= 5; roll++)
{
++freq[1 + rand.nextInt(4)];
}
System.out.println("Face\tFrequency");
for (int face = 0; face < freq.length; face++)
{
System.out.println(face + "\t" + freq[face]);
}
}
}
I tried to understand this on my own and I can pretty understand the rest aside from this one line
++freq[1 + rand.nextInt(4)];
which is located in the first for loop.
I tried to use a breakpoint there to see what's happening behind. What I can understand from the debugger is that every time the first for loop LOOPS, the indices of the freq array is assigned a new value by the random.nextInt.
What I can't understand there is the whole line. The ++freq is really confusing to me. It looks like it's incrementing? and after the ++freq is a bracket [ ] that has this inside
1 + rand.nextInt(4)
I already read the docs of the random class in java. The 1 there maybe used to add on the generated number, but why does it need to be inside this [ ], and what does ++freq mean before [ ]?
Solution
Your assessment is pretty correct.
You should remove adding 1 to the nextInt() call to keep the range of random numbers between 0..4 inclusive and stay within the bounds of your freq array.
Change it to: ++freq[rand.nextInt(4)];
rand.nextInt()
is randomly selecting the element in the array by randomly calculating which index to access (random number from 0 to 4).
The ++freq[index] is equivalent to the statement: Select the element from the freq array at index and then increment the value at that index by 1.
As an example. When you first declare freq: int freq[] = new int[5];
you will have an array of all 0's: freq[] = {0, 0, 0, 0, 0}
Then, in the loop you have this statement: ++freq[rand.nextInt(4)];
Let's assume rand.nextInt(4)
randomly chooses 3.
++freq[3];
Recall the array was initialized to all zeros, so freq[3]
, at this point = 0, or:
freq[3] = 0;
And finally, the ++ is a post-increment operator and will have the effect of incrementing the current value of freq[3] by 1, or:
++feq[3]; is equivalent to:
freq[3] = freq[3] + 1; is equivalent to:
freq[3] = 0 + 1; is equivalent to:
freq[3] = 1;
Hope that adds some clarity.
Answered By - pczeus