ArrayIndexOutOfBoundsException原因不明

时间:2017-01-28 06:53:23

标签: java

我正在编写一个创建迷宫作为二维数组的程序。我遇到了打嗝,那就是ArrayIndexOutOfBoundsException。它指向drawMaze方法中的maze[0][0] = "S"。我对此嗤之以鼻,我不知道它为什么会抛出错误。

import java.util.Random;

public class LA2_MazeSolver {

private int rows;
private int cols;
private String[][] maze = new String[rows][cols];

LA2_MazeInput mi = new LA2_MazeInput();

public void setNumRows(int numRows) {

    this.rows = numRows;

}

public void setNumCols(int numCols) {

    this.cols = numCols;

}

public int getNumRows() {

    return this.rows;

}

public int getNumCols() {

    return this.cols;

}

public void drawMaze() {

    Random r = new Random();

    maze[0][0] = "S";
    maze[rows - 1][cols - 1] = "D";
    int limit = ((rows * cols) / 3);

    for (int i = r.nextInt(limit) + 1; i < limit; i++) {

        maze[r.nextInt(rows) - 1][r.nextInt(cols) - 1] = "#";

    }

    for (int i = 0; i < maze.length; i++) {
        for (int c = 0; c < maze[0].length; c++) {

            if (!(maze[i][c].matches("#")) && !(maze[i][c].matches("S")) && !(maze[i][c].matches("D"))) {

                maze[i][c] = Integer.toString(r.nextInt(100) + 1);

            }

        }
    }

}

public void printMaze() {

}

/*public boolean isSolvable() {

    return solveMazeRecursively(this.rows, this.cols);

}

private boolean solveMazeRecursively(int row, int col) {

}*/

public void printResult() {

}
}

2 个答案:

答案 0 :(得分:2)

这很简单。您正在获得Array Index Out of Bound的异常,因为您超出了数组边界。

  

我遇到了打嗝,那就是ArrayIndexOutOfBoundsException。它指向“迷宫[0] [0] =”S“;”

您已在以下区块中声明了迷宫

private int rows;
private int cols;
private String[][] maze = new String[rows][cols];

请注意,您为“迷宫”指定了'rows'和'cols'的大小。但这些值分别为0和0。请注意,在初始化时,您没有为行和列提供值。因此,声明为类成员的int基元的默认值为0.

要解决此问题,请将行和列初始化为大于0的值。

答案 1 :(得分:0)

在Java中,您无法在构造函数之外创建private String[][] maze = new String[rows][cols];之类的定义。在代码中的那一点,rowcol的值尚未定义,因此private String[][] maze = new String[rows][cols];之类的行为不会有明确定义的行为(row和{ {1}}实际上可能是0,谁知道呢。

尝试这样的事情:

col

现在,当您创建 private int row; private int col; private String[][] maze; public LA2_MazeSolver(int row, int col) { this.row = row; this.col = col; maze = new String[row][col] } 对象时,您将动态创建一个使用正确大小的数组(例如LA2_MazerSolver)。