gpt4 book ai didi

Java ArrayIndexOutOfBounds 错误

转载 作者:行者123 更新时间:2023-12-01 07:22:25 26 4
gpt4 key购买 nike

所以我有一个数组 Canvas[256][256],它的随机索引 Canvas[r][r] (r 是随机的)设置为 1。然后我想循环遍历该数组以准确查看哪个索引是不是 0,然后随机选择一个点(上、下、左、右)并将该点也设置为 1。它在第一个循环中工作得很好,但之后给了我一个数组越界错误。

public static void checkPopulation() {
for(int x = 0; x < Canvas.length; x++) {
for(int y = 0; y < Canvas.length; y++) {
if(Canvas[x][y] != 0) {
particleDiffusion(x, y);
}
}
}

}

public static void particleDiffusion(int x, int y) {
Random r = new Random();
if(r.nextInt(3) == 0) {
Canvas[x+1][y] = 255;
} else if(r.nextInt(3) == 1) {
Canvas[x][y+1] = 255;
} else if(r.nextInt(3) == 2) {
Canvas[x-1][y] = 255;//THIS IS WHERE ERROR IS POINTING
} else if(r.nextInt(3) == 3) {
Canvas[x][y-1] = 255;
}
if(stepsTaken < diffusionStep) {
checkPopulation();
} else {
System.out.println("done");
return;
}
}

有人可以帮我解决我做错的事情吗?为什么它循环一次然后给出错误?

最佳答案

你检查x和y是否小于Canvas.length,然后你使用x+1和y+1作为数组索引,这就是原因。固定代码如下。

public static void checkPopulation() {
for(int x = 0; x < Canvas.length; x++) {
for(int y = 0; y < Canvas.length; y++) {
if(Canvas[x][y] != 0) {
particleDiffusion(x, y);
}
}
}
}

public static void particleDiffusion(int x, int y) {
Random r = new Random();
if(r.nextInt(3) == 0) {
if( x+1 < Canvas.length)
Canvas[x+1][y] = 255;
} else if(r.nextInt(3) == 1) {
if( y+1 < Canvas.length)
Canvas[x][y+1] = 255;
} else if(r.nextInt(3) == 2) {
if( x > 0)
Canvas[x-1][y] = 255;//THIS IS WHERE ERROR IS POINTING
} else if(r.nextInt(3) == 3) {
if( y > 0)
Canvas[x][y-1] = 255;
}
if(stepsTaken < diffusionStep) {
checkPopulation();
} else {
System.out.println("done");
return;
}
}

编辑:您还应该检查 x-1 和 y-1 不是负数。

关于Java ArrayIndexOutOfBounds 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32485760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com