线程" main"中的例外情况

时间:2015-12-02 23:44:38

标签: java arrays indexoutofboundsexception

我不知道为什么我的界限不正确以及为什么会抛出这个错误。

线程中的异常" 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();然后我得到错误,eclipse将我指向这行代码:

clearPath2D[right][down] = 4;

我认为这是因为我正在循环使用incorreclty。我找不到一个解决方案,用谷歌搜索了大约一个小时三天。

这不是所有代码,但这是我认为将其抛弃的部分。提前感谢您对错误的任何帮助。如果您需要整个代码,请告诉我。

编辑: 没关系,我弄清楚了。

我必须在数组的初始声明中添加1

在这种情况下,它意味着改变

clearPath2D = new int[gridSize][gridSize];

clearPath2D = new int[gridSize + 1][gridSize + 1];

1 个答案:

答案 0 :(得分:1)

您的当前问题出现在此部分代码中:

    if (currentStep.x == gridSize) {
        rightReached = 1;
        random = 1;
    }

    if (currentStep.y == gridSize) {
        bottomReached = 1;
        random = 0;
    }

您应该针对gridSize-1进行测试,因为这是最大有效索引。如:

    if (currentStep.x == gridSize-1) {
        rightReached = 1;
        random = 1;
    }

    if (currentStep.y == gridSize-1) {
        bottomReached = 1;
        random = 0;
    }