2014-11-05 57 views
1

我一直在測試arrayOutOfBounds異常時遇到問題。在下面的代碼中,我的if ... else語句應該可以防止騎士離開我的國際象棋棋盤,但是我仍然得到了例外。有人在這裏看到我的錯誤嗎?任何幫助表示讚賞!ArrayOutOfBounds測試代碼不起作用

public int[][] firstMoveChoice() { 
int knight = 0;  
x += 1; 
y += 2; 

if (x > board.length) { // this tests to make sure the knight does not move off the row 
    System.out.println("Cannot move off board on x axis"); 
    x -= 1; 
} 
else if (y > board.length) { // this tests to make sure the knight does not move off the column 
    System.out.println("Cannot move off board on y axis"); 
    y -= 2; 
} 
else { // this moves the knight when the above statements are false 
    board[x][y] = ++knight; 
    System.out.println("This executed"); 
} 

for(int[] row : board) { 
    printRow(row); 
} 
} 

這裏是最後的板,得到了印:

This executed 
1 0 0 0 0 0 0 0 
0 0 2 0 0 0 0 0 
0 0 0 0 3 0 0 0 
0 0 0 0 0 0 4 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 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8 
at knightstour.Moves.firstMoveChoice(Moves.java:53) 
at knightstour.KnightsTour.main(KnightsTour.java:24) 
Java Result: 1 
BUILD SUCCESSFUL (total time: 0 seconds) 

這裏是我的器ChessBoard類:

public class ChessBoard { 

int[][] board; 

public ChessBoard() { 
    this.board = new int[8][8]; 
} 
} 

這裏是我的printRow方法:

public static void printRow(int[] row) { 
    for (int i : row) { 
     System.out.print(i); 
     System.out.print(" "); 
    } 
    System.out.println(); 
} 

這是我的主要方法。當它調用起始位置時,它所做的只是將板[0] [0]分配給1.讓我知道是否需要實際的代碼。

public static void main(String[] args) { 

    MoveKnight myKnight = new MoveKnight(); 
    myKnight.startingLocation(); 
    myKnight.firstMoveChoice(); 
    myKnight.firstMoveChoice(); 
    myKnight.firstMoveChoice(); 
    myKnight.firstMoveChoice(); // this moves the knight off the board 
} 
+0

'>'必須'> =' - 在最後一次迭代,'y'是'8'和'board.length'也'8',所以條件不滿足於'>' – 2014-11-05 14:09:22

+0

你沒有實例化你的板子,你可以用你的板子對象聲明來顯示代碼嗎? – Cartier 2014-11-05 14:11:03

+0

> =表示大於或等於;因此,當你達到你設計的最大值時,它會循環一次,因爲布爾語句是正確的。 – Cartier 2014-11-05 14:12:46

回答

5

您的if條件必須是'> ='。嘗試:

if (x >= board.length) { // This tests to make sure the knight does not move off the row 
    System.out.println("Cannot move off board on x axis"); 
    x -= 1; 
} 
else if (y >= board.length) { // This tests to make sure the knight does not move off the column 
    System.out.println("Cannot move off board on y axis"); 
    y -= 2; 
} 
+0

好吧,我只是試過,它的工作原理。非常感謝你! – 2014-11-05 14:15:50

1

我猜你枚舉從0行/ COLS,而「長度」返回數組的真實長度,這樣形式的測試

if x > board.length 

是不正確的,因爲只有x{0,1,2,3,4,5,6,7}是應該是正確的,在你的情況下,8也不會大於8。改變這些條件

if x >= board.length 

同樣適用於y

+0

我很感謝你向我解釋!感謝您的時間! – 2014-11-05 14:16:29