繁体   English   中英

避免二维数组中的越界异常

[英]Avoid out of bounds exception in 2D array

我正在尝试解决一个使用二维数组的问题,即迷宫中的老鼠问题。

在检查试图编译的条件时,它发现一个数组索引越界异常......我如何检查值以使其不超出数组边界?

static void solveMaze(){

    int nSteps = 0; // Number of steps.
    int x = 0; int y = 0; // Starting point.

    boolean mazeCompleted = false;

    while (!mazeCompleted){

        if(x == maze.mazeMatrix.length && y == maze.mazeMatrix.length)
            mazeCompleted = true;

        else if(maze.mazeMatrix[x+1][y] == 0){ // Move right.
            maze.mazeMatrix[x+1][y] = 2;
            x++; nSteps++;
        }

        else if(maze.mazeMatrix[x-1][y] == 0){ // Move left.
            maze.mazeMatrix[x-1][y] = 2;
            x--; nSteps++;
        }

        else if(maze.mazeMatrix[x][y+1] == 0){ // Move down.
            maze.mazeMatrix[x][y+1] = 2;
            y++; nSteps++;
        }

        else if(maze.mazeMatrix[x][y-1] == 0){ // Move up.
            maze.mazeMatrix[x][y-1] = 2;
            y--; nSteps++;
        }

    }

    maze.printMatrix();
    System.out.println("Maze COMPLETE! - With a total of " + nSteps + " steps.");

}

之前尝试过使用两个“for”循环来防止越界,但我无法解决这个问题。

您的程序中有一个非常关键的错误。 你永远不会到达迷宫的尽头!

if(x == maze.mazeMatrix.length && y == maze.mazeMatrix.length)

引用越界的索引! 它应该是

if(x == maze.mazeMatrix.length - 1 && y == maze.mazeMatrix.length - 1)

在尝试搬到那里之前,您还需要检查是否可以并且应该搬家。 IE :

while (!mazeCompleted){

boolean moveRight = (x + 1 < mazeMatrix.length && maze.mazeMatrix[x+1][y] == 0 ? true : false);
boolean moveLeft = (x - 1 >= 0 && maze.mazeMatrix[x-1][y] == 0 ? true : false);
boolean moveUp = (y + 1 < mazeMatrix[x].length && maze.mazeMatrix[x][y+1] == 0 ? true : false);
boolean moveDown = (y - 1 >= 0 && maze.mazeMatrix[x][y-1] == 0 ? true : false);

和:

else if(moveRight) { // Move right.
        maze.mazeMatrix[x+1][y] = 2;
        x++; nSteps++;
}

等等。虽然看起来这确实是应该递归解决的问题,但好像迷宫中有任何循环一样,你最终会卡住并无限循环。

暂无
暂无

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

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