Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 避免二维数组中的越界异常_Java_Arrays_Indexoutofboundsexception - Fatal编程技术网

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

Java 避免二维数组中的越界异常,java,arrays,indexoutofboundsexception,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){

我试图解决一个使用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”循环来防止越界,但在这个问题上我就是不能走对角线。

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

if(x == maze.mazeMatrix.length && y == maze.mazeMatrix.length)
引用超出范围的索引!应该是

if(x == maze.mazeMatrix.length - 1 && y == maze.mazeMatrix.length - 1)
您还需要在尝试移动到那里之前检查您是否可以移动和应该移动。即:

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

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

你能分享堆栈跟踪吗?最简单的方法是使用2来表示循环。否则,您可以在递增/递减之前检查该值是否有效。例如:如果(x-->0){x--;}当x为零时,您尝试访问x-1。在尝试访问相邻单元格之前,您需要检查x和迷宫的大小是否为零以及迷宫的最大大小。@Dylan您的示例中是否要将x减量两次?不,对不起,如果(x>0){x--;}是我的意思,那么快速键入到是一个错误:x非常感谢:)!是的,这个问题应该用回溯法来解决,但是它也可以递归地解决,不是吗?这个问题应该用回溯法来解决。你的算法根本没有回溯。使用递归将允许您回溯。
else if(moveRight) { // Move right.
        maze.mazeMatrix[x+1][y] = 2;
        x++; nSteps++;
}