简体   繁体   English

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

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

I'm trying to solve a problem which uses a 2D array, the problem of a rat in a maze.我正在尝试解决一个使用二维数组的问题,即迷宫中的老鼠问题。

While checking the conditions trying to compile, it finds an Array index out of bounds exception... how can I check the values so it doesn't go out of the array bounds?在检查试图编译的条件时,它发现一个数组索引越界异常......我如何检查值以使其不超出数组边界?

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.");

}

Tried before with two "for" loops to prevent the out of bounds but I just can't go diagonal in this problem.之前尝试过使用两个“for”循环来防止越界,但我无法解决这个问题。

You have a pretty crucial bug in your program.您的程序中有一个非常关键的错误。 You will never reach the end of the maze!你永远不会到达迷宫的尽头!

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

references indices that are out of bounds!引用越界的索引! It should be它应该是

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

You also need to check to see whether you can & should move before you try to move there.在尝试搬到那里之前,您还需要检查是否可以并且应该搬家。 IE : 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);

And:和:

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

etc. Although it does seem like this is something that should be solved recursively, as if there are any loops in the maze you will end up getting stuck and infinite looping.等等。虽然看起来这确实是应该递归解决的问题,但好像迷宫中有任何循环一样,你最终会卡住并无限循环。

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

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