我正在编写一个程序,将迷宫创建为二维数组。我遇到了一个问题,那就是 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() {
}
}
最佳答案
很简单。由于超出了数组边界,您将收到数组索引越界异常。
I've run into a hiccup, and that is ArrayIndexOutOfBoundsException. It is pointing to "maze[0][0] = "S";"
您已在以下区 block 中声明迷宫
private int rows;
private int cols;
private String[][] maze = new String[rows][cols];
请注意,您正在为“迷宫”指定“行”和“列”的大小。但这些值分别是0和0。请注意,您在初始化时没有为 rows 和 cols 赋予值。因此声明为类成员的 int 基元的默认值为 0。
要解决此问题,请将行和列初始化为大于 0 的值。
关于java - ArrayIndexOutOfBoundsException 原因未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41907175/