我正在尝试生成这个2D数组迷宫10×10,每行10行数字0-9,但我不断得到数组超出界限异常。我仔细检查了我的索引和循环格式,一切看起来都很标准。
public class MazeDemo {
public static void main(String[] args) {
Maze maze = new Maze(10, 10);
maze.generate();
}
}
class Maze {
int N, M;
int[][] cell = new int[N][M];
public Maze(int N, int M) {
this.N = N;
this.M = M;
}
public void generate() {
for (int i = 0; i < N; i++) {
int counter = 0;
for (int j = 0; i < M; j++) {
cell[i][j] = counter;
counter++;
}
}
display(cell, 10, 10);
}
public static void display(int a[][], int N, int M) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
System.out.print(a[i][j]);
}
}
}
}
这里发生了什么?为什么我会超出界限范围?
答案 0 :(得分:2)
当您声明cell
时,N
和M
为0
。将其更改为
int N, M;
int[][] cell;
public Maze(int N, int M) {
this.N = N;
this.M = M;
this.cell = new int[N][M]; // <-- add this.
}
在generate
中,这是
for (int j = 0; i < M; j++) {
应该是
for (int j = 0; j < M; j++) {
答案 1 :(得分:0)
问题出在generate
方法中:
for (int j = 0; i < M; j++)
^
它应该是:
for (int j = 0; j < M; j++)