簡體   English   中英

基本Java數組和For循環

[英]Basic Java Array and For Loop

我正在學習Java課程並且一遍又一遍地閱讀相同的解釋,我只是想確保我正確地理解它。

他們提供的課程中的例子是骰子滾動游戲,他們希望看到每個數字的滾動頻率。

我不確定的代碼片段是這樣的:

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

我理解這一部分: 1+rand.nextInt(6)

但我不明白這一部分: ++freq以及它如何計算結果

我理解這一點(以我的例子為例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
}

這個對嗎?

int[] freq = new int[7];

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

在上面的代碼中, rand.nextInt(6)返回一個從0到5的值,用於訪問數組freq的相關整數值

++freq part將訪問的整數值增加1。

示例:如果rand.nextInt(6)返回2

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

但是,從1 + rand.nextInt(6) ,0永遠不會產生。 因此,應該忽略freq數組的第一個元素。

freq[n]會給你nth面的頻率。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM