我一直在測試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
}
'>'必須'> =' - 在最後一次迭代,'y'是'8'和'board.length'也'8',所以條件不滿足於'>' – 2014-11-05 14:09:22
你沒有實例化你的板子,你可以用你的板子對象聲明來顯示代碼嗎? – Cartier 2014-11-05 14:11:03
> =表示大於或等於;因此,當你達到你設計的最大值時,它會循環一次,因爲布爾語句是正確的。 – Cartier 2014-11-05 14:12:46