JAW*_*025 -2 java arrays random variables loops
我试图将数组中的值设置为变量.这是我的代码:
//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;
}
Run Code Online (Sandbox Code Playgroud)
我用错误标记了该行,返回的错误是:"未捕获的异常抛出...".我究竟做错了什么???提前致谢.
编辑 - - -
这是完整的例外:
Uncaught exception thrown in Thread[LWJGL Renderer Thread,5,main]
Run Code Online (Sandbox Code Playgroud)
我使用y来生成随机高斯,然后将其转换为浮点值并将x更改为该浮点值
我很确定这就是那条线,因为这就是我的编译器告诉我的.
我猜你得到两个例外之一:
你得到一个NullPointerException因为已初始化地图null.使用例如分配非空值:
private float[] map = new float[25];
Run Code Online (Sandbox Code Playgroud)您得到的是IndexOutOfBoundsException因为您使用的是基于1的索引而不是基于0的索引.
改变这个:
int n = 1;
while(n <= 25) {
// etc..
n = n + 1;
}
Run Code Online (Sandbox Code Playgroud)
到这个for循环:
for (int n = 0; n < 25; ++n) {
// etc..
}
Run Code Online (Sandbox Code Playgroud)