我在测试arrayOutOfBounds异常时遇到了麻烦。在下面的代码中,我的if ... else语句应该阻止骑士离开我的棋盘,但是我仍然得到例外。有没有人在这看到我的错误?任何帮助表示赞赏!
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();
}
这是我的主要方法。当它调用起始位置时,它所做的就是将board [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 :(得分: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;
}
答案 1 :(得分:1)
我猜你从0中枚举行/列,而“length”返回数组的真实长度,所以测试表格
if x > board.length
不正确,因为x
中只有{0,1,2,3,4,5,6,7}
应该是正确的,在您的情况下,8也不会大于8
。将这些条件更改为
if x >= board.length
同样适用于y