java - ArrayIndexOutOfBoundsException 原因未知

标签 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() {

}
}

最佳答案

很简单。由于超出了数组边界,您将收到数组索引越界异常。

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/

相关文章:

java - 在 Android 上使用 XMLBeans

java - 基于 REST token 的身份验证不起作用

java - 有没有办法用Java在Linux上以协作方式播放WAV文件?

java - 尝试通过URL访问tomcat中的xml文件,出现404错误

java - Spring-cglib 代理类层次结构中的行为

java - 如何更新 JavaFX Canvas ?

java - 将字符串分成三分之一

java - 在Java中的方法中更新对象

java - 在java中获取文件扩展名

java - SSLEngine 展开() javax.crypto.BadPaddingException : bad record MAC