gpt4 book ai didi

java - ArrayOutOfBounds 测试代码不起作用

转载 作者:行者123 更新时间:2023-11-29 07:00:39 25 4
gpt4 key购买 nike

我在测试 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
}

最佳答案

您的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;
}

关于java - ArrayOutOfBounds 测试代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26759174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com