2017-05-25 89 views
-1

我想在過程中編寫一段簡單的代碼來創建Connect 4遊戲。我試圖創建和顯示6 7板因爲這樣,我終於可以放下X和O的:Java錯誤:線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:6

|||||||| 
|||||||| 
|||||||| 
|||||||| 
|||||||| 
|||||||| 

我不斷收到錯誤:異常線程「main」 java.lang.ArrayIndexOutOfBoundsException:6

public static void printConnect4Board(){ 
final int WIDTH = 6; 
final int HEIGHT = 7; 
int [] [] connect4Board = new int [WIDTH][HEIGHT]; 
Scanner input = new Scanner(System.in); 
for(int w = 0; w < connect4Board.length; w++){ 
    for(int h = 0; h < connect4Board[w].length; h++){ 
     System.out.println(connect4Board[w][h] + "|"); 
    } 
    System.out.println(); 
} 

}

任何幫助將不勝感激。謝謝。

+0

應該是'connect4Board [H]在第二到最後一行[W]'。 –

回答

1

交換你的索引和變化從的println打印:

public static void printConnect4Board(){ 
    final int WIDTH = 6; 
    final int HEIGHT = 7; 
    int [] [] connect4Board = new int [WIDTH][HEIGHT]; 
    Scanner input = new Scanner(System.in); 
    for(int h = 0; h < HEIGHT; h++){ 
     System.out.print("|"); 
     for(int w = 0; w < WIDTH; w++){ 
      System.out.print("|"); 
     } 
     System.out.println(); 
    } 
} 
+0

再看一遍,這個不會拋出任何異常 – nge

+0

現在輸出結果是:0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | – user7729282

+0

好吧,應該這樣做,以前的代碼是打印HxW(7x6),而我認爲OP要WxH(6x7)。 – nge

相關問題