2016-12-03 51 views
-1

我正在嘗試創建一個將玩遊戲連接四個的程序。當試圖插入它沒有問題編譯一個計數器,但是當我嘗試輸入一些進入程序將顯示消息:出境異常:6

java.lang.ArrayIndexOutOfBounds例外:6

,同時凸顯線

System.out.print("|" + " " + board[row][col]); 

所涉及的滿的方法是:

public static void playGame() { 
    Scanner input = new Scanner(System.in); 
    String[][] board = new String[6][7]; 
    for (int i = 0; i < board.length; i++) 
     for (int j = 0; j < board[i].length; j++) 
      board[row][col] = " "; 
    int column = 0; 
    for (int i = 0; i <= 6; i++) { 
     displayBoard(); 
     String turn = "R" ; 
     System.out.print("Red player enter number 0 - 6: "); 
     column = input.nextInt(); 
     System.out.print("|" + " " + board[row][col]); 
     board[row][col] = "R"; 
     displayBoard(); 
    } 
} 
+3

你爲什麼不使用'i'和'j',而不是'row'和'col'?你的代碼沒有意義。請提供[mcve]。 – Gendarme

+1

你說我<= 6,你不能去登機[6] [#],這就是爲什麼你越來越出界的錯誤。使用我

回答

1

你需要你的基地離我董事會的長度,而不是一些神奇的數字

//use the i & j's to set your board 
for (int i = 0; i < board.length; i++) 
    for (int j = 0; j < board[i].length; j++) 
     board[i][j] = " "; 


for (int i = 0; i < board.length; i++) { 
    displayBoard(); 
    String turn = "R" ; 
    System.out.print("Red player enter number 0 - 6: "); 
    column = input.nextInt(); 
    System.out.print("|" + " " + board[i][column]); 
    board[i][column] = "R"; 
    displayBoard(); 
}