2012-06-20 267 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;