0

Array as Counters in Java, can anyone help me understand the program below.

class RollaDice{ public static void main (String[] args){ Random Rand = new Random(); it freq[] = new int[7]; for (int roll=1;roll<100;roll++){ ++freq[1+rand.nextInt(6); } System.out.println("Face\tFrequency"); for (int face=1;face<freq.length;face++){ System.out.println(face+"\t"+freq[face]); } } } RollaDice will roll between 1-6 and the above program displays the number of times an index is visited with a particular value in it. The value randomly generated between 1 to 6 using the utility called Random. That is the theoretical part but I am finding it hard to understand the actual logic. Any one with the explanation ? I have been following the Buckys java tutorial and if you want more info on this, take a look https://www.youtube.com/watch?v=pHxtKDENDdE&list=PL484D73FA74A11AC9&index=30

13th Aug 2017, 3:39 PM
Vivek Zacharia Muricken
Vivek Zacharia Muricken - avatar
1 Odpowiedź
+ 3
You have a few syntax errors here 😜. But I assume what you're stuck on is this: ++freq[1+rand.nextInt(6)]; For the sake of simplifying this, allow me to do this: int randIndex = 1 + rand.nextInt(6); ++freq[randIndex]; Hopefully now it's easier to see. Initially you created the array: int freq = new int[7]; new int[7]; Will create an array of size 7, all elements having their default values. So, it looks like this: {0,0,0,0,0,0,0} Now when we do: int randIndex = 1 + rand.nextInt(6); This will get a random number from 0-5 Then add it by 1. So, a random number from 1-6. ***************** *Note* Normally I Do NOT recommend using '6', use a variable or the length of the array instead. This improves the flexibility and readability of your program. (Flexibility since you can easily change things, readability since I know why you wrote '6'). Like so: int randIndex = 1 + rand.nextInt(freq.length()-1); However in this case I suppose it's ok since dice always have 6 sides. Although, you could do something like this: final int DICE_SIDES = 6; and use that local constant instead. ********************** Anyway.. So we now know it gets a random number. But what the heck is ++freq[randIndex]; ?? Well, remember from the java course ++x will increment the value by 1. x in this case is the element in the array. So, we are incrementing an element at a random index in the array by 1!!
13th Aug 2017, 4:31 PM
Rrestoring faith
Rrestoring faith - avatar