2012-06-20 266 views
0

我有一個快速問題,我正在測試Math.random的功能。我試圖將(int) (Math.random()*6)+1的結果分配給一個數組來存儲這些值。但是我收到一個錯誤,它不是一個聲明。有人可能提供一些指導?將math.random賦值給數組

public shoes(int[] pairs) 
{ 
    System.out.println("We will roll go through the boxes 100 times and store the input for the variables"); 
    for(int i=0; i < 100; i++) 
    { 
     //("Random Number ["+ (i+1) + "] : " + (int)(Math.random()*6)); 
     int boxCount[i] = (int) (Math.random()*6) + 1; 
    } 
} 
+1

不要使用'的Math.random()'。 ..它不適合你的目的,很難閱讀。使用'隨機rand = new Random();'和'rand.nextInt(6)+1;'代替。 –

+0

爲什麼你declearing int boxCount [i] = ...這樣,它沒有任何意義。 – loki

+0

你的方法沒有返回類型。 –

回答

5

您有語法錯誤。 boxCount尚未實例化,並且不是已知類型。在嘗試使用之前,您需要創建boxCount陣列。見下面的例子:

public void shoes(int[] pairs) 
{ 
    System.out.println("We will roll go through the boxes 100 times and store the input for the variables"); 
    int boxCount[] = new int[100]; 
    for(int i=0; i < boxCount.length; i++) 
    { 
     //("Random Number ["+ (i+1) + "] : " + (int)(Math.random()*6)); 
     boxCount[i] = (int) (Math.random()*6) + 1; 
    } 
} 
+0

謝謝cklab,它現在可以工作! – SaintClaire33

3
int boxCount[i] = (int) (Math.random()*6) + 1; 

這行代碼看起來像你正試圖創建一個數組或東西。

您要創建陣列boxCount您的循環之前:

int boxCount[] = new int[100]; 

然後你就可以在你的循環做到這一點:

boxCount[i] = (int) (Math.random()*6) + 1;