import java.util.Random;
public class DemoArrayElement {
    public static void main(String arg[]) {
        Random rand = new Random();
        int[] freq = new int[7];
        for (int roll = 1; roll < 10; roll++) {
            ++freq[1 + rand.nextInt(6)];
        }
        System.out.println("FACE\tFREQUENCY");
        for (int face = 1; face < freq.length; face++) {
            System.out.println(face + "\t\t" + freq[face]);
        }
    }
}
Can someone please explain me this ++freq[1+rand.nextInt(6)]; line of code.
This program simulates rolling a die 10 times. The array freq is used to count the frequencies each face value is rolled - the index represents the face value and the content the number of times it was rolled. So, e.g., freq[3] contains the number of times 3 was rolled.
Let's take a look at ++freq[1+rand.nextInt(6)]; and take it apart:
rand.nextInt(6) calls Java's random number generator (a java.util.Random instance) and asks it for a uniformly distributed random number between 0 and 5 (inclusive). Adding 1 to it gives you a random face value form a die - a number between 1 and 6.
Accessing this index in the freq array (freq[1+rand.nextInt(6)]), as noted above, will return the number of times this face value was randomly encountered. Since we just encountered it again, this number is incremented (the ++ operator).
frec is an array containing 7 numeric elements.
++freq[1+rand.nextInt(6)]; means pre-increment a random element from an array.
Example: if the second element from the array is 5:
++freq[1]; will make it 6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With