避免2D数组中的越界异常

时间:2014-03-30 17:15:33

标签: java arrays indexoutofboundsexception

我正在尝试解决使用2D阵列的问题,即迷宫中老鼠的问题。

在检查尝试编译的条件时,它会发现一个数组索引超出范围异常...我如何检查这些值,使它不会超出数组边界?

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”循环以防止越界,但我不能在这个问题上走对角线。

1 个答案:

答案 0 :(得分:0)

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

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

引用超出范围的索引!它应该是

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

您还需要检查是否可以&在你试图移动之前应该移动。 I.E. :

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++;
}

等。虽然看起来确实应该以递归方式解决这个问题,好像迷宫中有任何循环一样,你最终会陷入困境并且无限循环。