samedi 25 août 2018

Basic Java Array and For Loop

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?




Aucun commentaire:

Enregistrer un commentaire