1

I am taking a Java class and have read the same explanation over and over and I just want to make sure I am understanding it correctly.

The example in the class they provide is a dice rolling game and they want to see the frequency of rolls per number.

The code snippet that I am uncertain on is this:

for(int roll = 1; roll < 1000; roll++){
    ++freq[1+rand.nextInt(6)];
}

I understand this part: 1+rand.nextInt(6)

But I don't understand this part: ++freq and how it tallys the results

I am understanding this as (with the example I rolled a 4):

for(int roll = 1; roll < 1000; roll++){
    ++freq[4];
    //all indexes in freq are == 0 to start
    //freq[4] is index 4 in the array. It was 0 but is now == to 1
    //freq[0], freq[1], freq[2], freq[3], freq[5], and freq[6] are all still == to 0
}

for(int roll = 1; roll < 1000; roll++){
    ++freq[6];
    //freq[6] is index 6 in the array. It was 0 but is now == to 1
    //freq[0], freq[1], freq[2], freq[3], and freq[5] are all still == to 0
    //freq[4] and freq[6] are both == to 1
}

Is this correct?

2
  • 2
    ++freq[4] is short for freq[4] = freq[4] + 1 Commented Aug 25, 2018 at 15:26
  • 1
    For the record, ++freq[1+rand.nextInt(6)]; is rather unclear code. Unless you are developing on a 2 inch screen or are penalised for writing more lines of code, it is much clearer to write it as a variable int roll = 1 + rand.nextInt(6); and an increment ++freq[roll];. Commented Aug 25, 2018 at 15:31

1 Answer 1

3
int[] freq = new int[7];

    for(int roll = 1; roll < 1000; roll++){
        ++freq[1+rand.nextInt(6)];
    }

In the above code rand.nextInt(6) returns a value from 0 to 5 which is used to access the relevant integer value of the array freq

++freq part increases the accessed integer value by 1.

Example: if rand.nextInt(6) returns 2,

freq[1 + 2] = freq[1 + 2] + 1;

However, from 1 + rand.nextInt(6), 0 is never produced. Therefore, the first element of freq array should be ignored.

freq[n] will give you the frequency of the nth face.

Sign up to request clarification or add additional context in comments.

1 Comment

this was a super helpful breakdown. Thank you!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.