java ArrayOutOfBounds测试代码不工作
我在测试arrayOutOfBounds异常时遇到了麻烦。在下面的代码中,我的if。。。否则的话,我会阻止骑士离开我的棋盘,不过我还是有例外。有人看到我的错误了吗?感谢您的帮助
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)
这是我的棋盘课:
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
}
# 1 楼答案
我猜您是从0枚举行/列,而“length”返回数组的真实长度,所以对表单进行测试
是不正确的,因为只有
x
在{0,1,2,3,4,5,6,7}
中才是正确的,而且在您的情况下,8也不大于8
。将这些条件更改为这同样适用于
y
# 2 楼答案
你的
if
条件必须是“>;=”。试试看: