繁体   English   中英

线程“ main”中的异常

[英]Exception in thread “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;

我认为这是因为我循环不正确。 我无法找到解决方案,并且在三个不同的日子里用谷歌搜索了大约一个小时。

这不是全部的代码,但这是我认为正在抛弃的部分。 预先感谢您对错误的任何帮助。 如果您需要完整的代码,请告诉我。

编辑:没关系,我想通了。

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

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

clearPath2D = new int[gridSize][gridSize];

clearPath2D = new int[gridSize + 1][gridSize + 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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM