我不知道为什么我在我的范围内不正确以及为何引发此错误。线程“main”中的异常
在线程异常 “主” java.lang.ArrayIndexOutOfBoundsException
private int gridSize = 3;
private Point currentStep = new Point(0, 0);
private Point firstStep = new Point(0, 0);
private Point lastStep = new Point(gridSize, gridSize);
private int pedometer = 0;
private int random;
private int down = 0;
private int right = 0;
private byte bottomReached = 0;
private byte rightReached = 0;
private int[][] clearPath2D;
public void createWalk2D() {
clearPath2D = new int[gridSize][gridSize];
for (currentStep = firstStep; currentStep != lastStep; pedometer++) {
step2D();
if (rightReached == 1 && bottomReached == 1) {
break;
}
}
clearField();
}
public void step2D() {
random = stepRand.nextInt();
// add a new step to the current path
currentStep.setLocation(right , down);
clearPath2D[right][down] = 4;
// calculates the next step based on random numbers and weather a side
// is being touched
if (currentStep.x == gridSize) {
rightReached = 1;
random = 1;
}
if (currentStep.y == gridSize) {
bottomReached = 1;
random = 0;
}
// decides the direction of the next step
if (random >= 0.5 && bottomReached == 0) {
down++;
} else if (random < 0.5 && rightReached == 0) {
right++;
} else if (rightReached == 1 && bottomReached == 1) {
done = true;
}
}
所以我所说的createWalk2D();然后我得到了错误和日食指向我的这一行代码:
clearPath2D[right][down] = 4;
我认为这是因为我在循环incorreclty。我一直无法找到解决方案,并在三个不同的日子里搜索了大约一个小时。
这不是所有的代码,但这是我认为是抛弃它的部分。提前感谢您对错误的任何帮助。如果你需要整个代码,请让我知道。编辑: 没关系我想通了。
我在这种情况下,以1添加到阵列
的初始宣布它意味着改变
clearPath2D = new int[gridSize][gridSize];
到
clearPath2D = new int[gridSize + 1][gridSize + 1];
自己调试代码。在行'clearPath2D [right] [down] = 4'输出到控制台前的值为'right','clearPath2D.length','down'和'clearPath2D [right] .length'。您的右侧和下侧值应始终小于数组的长度。 –
'clearField();'做了什么? –
可能的重复[什么导致java.lang.ArrayIndexOutOfBoundsException,以及如何防止它?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how- do-i-prevent-it) – Raf