2011-06-19 31 views
0
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)];是那條線意味着插入每個索引的隨機數?可能會有人解釋這個java循環對我來說

+0

我假設你的意思是行數++數[1 + rand.nextInt(6)];'? –

+0

'++ number [1 + rand.nextInt(6)]'將數組'number'的隨機成員1到6增加一個 – PeterT

+0

您正在預先遞增數組的一個元素,同時將霧擴散到整個你的代碼在這裏。這裏發生的事情是,一個理貨正在增加。我會這樣做:number [1 + rand.nextInt(6)] + = 1; – ncmathsadist

回答

0

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

生成1和6之間的隨機數。數組number的適當索引基於隨機值遞增。該操作多次循環。最後,第二個循環用於打印每個值的打印次數。

但是,number數組的0索引從未被此代碼使用。實際上,這是浪費的空間,必須(並且)在第二個循環中考慮。

2
++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; 
+0

oky和++數字意味着什麼,它等於數字[1] = xxx然後數字[2] = xxx? – user805752

+0

@ user805752,否,這意味着它將存儲在數組的給定隨機索引處的元素的值遞增1。它相當於'number [index] = number [index] + 1;'就像我在答案中顯示的那樣。 –

+0

和(int roll = 1; roll <100; roll ++){mean?請給我步驟! – user805752

0

它在做什麼:

  1. 創建具有默認種子的隨機數發生器。
  2. 創建陣列具有7個元素(通過6索引爲0)
  3. 循環99次(與輥從1至99)
  4. 正如其他人所說,遞增所述陣列元件中的一個由一個處的值隨機。請注意,零指數永遠不會增加。
  5. 的代碼的其餘部分通過6.

輸出已經在索引1被計數的值,作者已經忽略了零索引是氣味的比特的事實。

0
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

現在明白了所有的代碼,所以我敢肯定,你會知道它做什麼。注意你的數組的第一個索引是零,並且永遠不會改變。

相關問題