2016-05-01 71 views
0

我想要生成這個二維陣列迷宮10 10與數字0-9在每行10行,但我不斷收到數組超出界限例外。我再次檢查我的索引和循環格式,一切都看起來很標準。爲什麼我不能生成這個10x10二維數組?

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

這是怎麼回事?爲什麼我會遇到越界異常?

回答

2

當您聲明cell,NM0。將其更改爲類似

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; j < M; j++) { 
+0

@ Elliot有兩個問題,爲什麼把數組放在指定的構造函數中,其次是爲什麼有這種格式的語法?謝謝 – SkyZ

+0

@SkyZ當你說'int N,M;'時,因爲'N'和'M'是原始的'int's,所以它們的值爲'0'。如果你不把初始化放在構造函數中,你會得到一個數組''[0] [0]'。至於語法的格式,它覆蓋了[JLS-15.10.1。數組創建表達式](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.10.1) –

0

的問題是在generate方法:

for (int j = 0; i < M; j++) 
       ^

它應該是:

for (int j = 0; j < M; j++) 
相關問題