简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM