将math.random值分配给数组

时间:2012-06-20 19:20:08

标签: java arrays for-loop

我有一个简单的问题,我正在测试Math.random功能。我试图将100个框中每个框的(int) (Math.random()*6)+1结果分配给一个数组来存储值。但我收到一个错误,它不是一个声明。有人可以提供一些指导吗?

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;
   }
}

2 个答案:

答案 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;
    }
}

答案 1 :(得分:3)

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

这行代码看起来像是在尝试创建数组或其他东西。

您希望在for循环之前创建数组boxCount

int boxCount[] = new int[100];

然后你可以在循环中执行此操作:

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