Java 如何将变量添加到数组中
我试图将数组中的值设置为变量。这是我的密码:Java 如何将变量添加到数组中,java,arrays,variables,loops,random,Java,Arrays,Variables,Loops,Random,我试图将数组中的值设置为变量。这是我的密码: //init the array as a float //I have tried to put a value in the brackets, but it returns a different error. //I initialized it this way so I could call it from other methods private float[] map; // generate a "seed" for the a
//init the array as a float
//I have tried to put a value in the brackets, but it returns a different error.
//I initialized it this way so I could call it from other methods
private float[] map;
// generate a "seed" for the array between 0 and 255
float x = generator.nextInt(256);
int n = 1;
// insert into the first 25 slots
while(n <= 25) {
// here's my problem with this next line
map[n] = x;
double y = generator.nextGaussian();
x = (float)Math.ceil(y);
n = n + 1;
}
我用y来生成一个随机高斯分布,然后把它转换成一个浮点值,然后把x转换成那个浮点值
我很确定这是那一行,因为这是我的编译器告诉我的。我猜你会得到两个例外中的一个:
NullPointerException
,因为您已将映射初始化为null
。使用以下命令分配非空值,例如:
private float[] map = new float[25];
索引AutofBoundsException
,因为您使用的是基于1的索引,而不是基于0的索引int n = 1;
while(n <= 25) {
// etc..
n = n + 1;
}
你能发布更多的例外情况吗。您还可以展示地图是如何定义的吗?什么是
map
?y
是做什么的?什么类型的“地图”?错误的全部信息是什么?可能不是下一行吗?(generator.nextGaussian();)太本地化了。我怎么知道它太本地化了?没有办法为这个问题写一个好标题。1) 阅读异常,发布异常,以某种有意义的方式使用异常来解决问题2)发布所有适用的代码。此外,作为nit,不可能向数组中添加变量——只能添加值。嗯,-1是因为没有实际听取注释和更新问题。@JAW1025:所以。。。你要告诉我们你得到的异常是什么类型的吗?我的答案只是我最好的猜测。你发布的信息太少,我无法确定。只是尝试了一下,完美的回答,修复了所有问题,谢谢!(很抱歉第一次不清楚。)
int n = 1;
while(n <= 25) {
// etc..
n = n + 1;
}
for (int n = 0; n < 25; ++n) {
// etc..
}