Line by line:
Random rand = new Random();
create new instance of the Random object, this is responsible for the creation of random numbers.
int[] freq = new int[7];
create a new int array that can store 7 elements, with indices from 0...6. It is worth noting that in Java
, the ints stored in the array are initialized to 0
. (This is not true for all languages, an example being C
, as in C
the int arrays initially store memory junk data, and must be explicitly initialized to zero).
for(int roll = 1; roll < 10; roll++)
this rolls 9 times (because 1...9, but it's better practice to go from 0)
(++freq[1 + rand.nextInt(6)]);
this line is something that you shouldn't ever do in this sort of fashion, because it's a monstrosity as you can see.
Do something like this:
for(int roll = 0; roll < 9; roll++)
{
int randomNumber = rand.nextInt(6); //number between 0...5
int index = 1 + randomNumber; //number between 1...6
freq[index]++; //increment the number specified by the index by 1
//nearly equivalent to freq[index] += 1;
}
So basically it randomizes the number of 9 dice throws, and stores the dice throw count (or so it calls it, frequency) in the array.
Thus, it's simulating 9 dice throws (numbers from 1...6), and each time it "rolls" a particular number, it increases the number stored in the array at that specific location.
So in the end, if you say:
for(int i = 1; i <= 6; i++)
{
System.out.println("Thrown " + freq[i] + " times of number " + i);
}
Then it will be clearly visible what's happened.