连接4检查获胜方法抛出索引越界错误



我在测试用例中检查获胜时收到的错误是一个"java.lang.ArrayIndexOutOfBoundsException"错误很抱歉,如果这个问题以前可能被问过,我已经尝试过寻找其他解决方案,但找不到。所以我希望这是好的。该项目的代码可以在这里看到:

public class testClass {

static int[][] board1 = {
{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, 0, 0},
{0, 0, 2, 2, 2, 2, 0},
};

static int[][] board2 = {
{0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
};

static int[][] board3 = {
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0},
{0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 1, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0},
};

static int redCount, ylwCount;


public static void main(String[] args) {
horizontalWin();
verticalWin();
diagonalWin();
}

public static void horizontalWin() {
for (int i = 0; i < 4; i++) {
if (board1[5][2 + i] == 1) {
redCount++;
} else if (board1[5][2 + i] == 2) {
ylwCount++;
}

if (redCount == 4) {
System.out.println("Red wins");
} else if (ylwCount == 4) {
System.out.println("Yellow wins");
}
}
redCount = 0;
ylwCount = 0;
}

public static void verticalWin() {
for (int i = 0; i < 4; i++) {
if (board2[1 + i][1] == 1 || board2[1 - i][1] == 1) {
redCount++;
} else if (board2[1 - i][1] == 2 || board2[1 - i][1] == 2) {
ylwCount++;
}

if (redCount == 4) {
System.out.println("Red wins");
} else if (ylwCount == 4) {
System.out.println("Yellow wins");
}
}
redCount = 0;
ylwCount = 0;
}

public static void diagonalWin() {
for (int i = 0; i < 4; i++) {
if (board3[5 + i][2 + i] == 1 || board3[5 - i][2 - i] == 1) {
redCount++;
} else if (board3[5 + i][2 + i] == 2 || board3[5 - i][2 - i] == 2) {
ylwCount++;
}

if (redCount == 4) {
System.out.println("Red wins");
} else if (ylwCount == 4) {
System.out.println("Yellow wins");
}
}
redCount = 0;
ylwCount = 0;
}
}

在方法对角线Win((中,board3[5+i][2+i]超过了board3的维度(即7X6(。

一旦i=1:board3[5+i][2+i]=board[6][3]

并且阵列中不存在板[6][3]。

最新更新