簡體   English   中英

可能有人會為我解釋這個java循環

[英]could some one explane this java loop for me

import java.util.Random;

class arel {
    public static void main(String args[]){
        Random rand = new Random();
        int[] number = new int[7];
        for(int roll = 1; roll < 100; roll++){
            ++number[1+rand.nextInt(6)];
        }
        System.out.println("Index\tValue");
        for(int count = 1; count<number.length; count++){
            System.out.println(count+"\t"+number[count]);
        }
    }
}

++number[1+rand.nextInt(6)]; 該行是否意味着為每個索引插入隨機數?

++number[1 + rand.Next(6)];

類似於:

// get a random number between 1 and 6
int index = 1 + rand.nextInt(6); 

// increase the element of the array at the given random index by 1
number[index] = number[index] + 1; 

++number[1+rand.nextInt(6)]; 利用Java中的數組是0初始化和操作順序的事實。

生成1到6之間的隨機數。 基於隨機值遞增陣列number的適當索引。 此操作多次循環。 最后,使用第二個循環打印出每個值的打印次數。

但是,此代碼從不使用number數組的0索引。 實際上,它是浪費的空間,必須(和)在第二個循環中占用。

它正在做什么:

  1. 使用默認種子創建隨機數生成器。
  2. 創建一個包含7個元素的數組(索引為0到6)
  3. 循環99次(滾動從1到99)
  4. 正如其他人所說的那樣,隨機地將一個數組元素的值遞增一。 請注意,零索引永遠不會遞增。
  5. 其余代碼輸出已在索引1到6中計數的值。

作者忽略零指數的事實有點嗅覺。

int[] number = new int[7]; // first index=0, last=6. 
                           // After creation all elements are 0

在for循環中,你調用99行: ++number[1+rand.nextInt(6)];

++number[index]; // it's the same: number[index]=number[index]+1

rand.nextInt(n)方法返回0..n-1之間的隨機整數。 的javadoc

在您的示例中,您向該隨機數添加一個,因此您在以下之間有一個隨機數:1..6

現在你可以理解所有的代碼,所以我相信你會知道它的作用。 請注意,您的數組的第一個索引為零,並且永遠不會更改。

暫無
暫無

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

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