java 将 math.random 值分配给数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11126660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assigning math.random value to array
提问by BV45
I have a quick question I am testing out the Math.random functionality. I am trying to assign the result from the (int) (Math.random()*6)+1
for each one of the 100 boxes to an array to store the values. But I am getting an error that it is not a statement. Can someone possibly offer some guidance?
我有一个简单的问题,我正在测试 Math.random 功能。我试图将(int) (Math.random()*6)+1
100 个盒子中的每一个的结果分配给一个数组来存储值。但我收到一个错误,它不是一个声明。有人可以提供一些指导吗?
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;
}
}
回答by cklab
You have a syntax error. boxCount
has not been instantiated and is not a known type. You need to create the boxCount
array before you attempt to use it. See example below:
您有语法错误。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;
}
}
回答by carmenism
int boxCount[i] = (int) (Math.random()*6) + 1;
This line of code looks like you are trying to create an array or something.
这行代码看起来像您正在尝试创建一个数组或其他东西。
You want to create the array boxCount
BEFORE your for loop:
您想boxCount
在 for 循环之前创建数组:
int boxCount[] = new int[100];
Then you can do this in your loop:
然后你可以在你的循环中做到这一点:
boxCount[i] = (int) (Math.random()*6) + 1;