java - 数组索引越界?

标签 java eclipse

此方法应在开始时和经过一些 Action 后确定游戏是否结束。

public boolean isGameOver() {
    Point[] player1 = new Point[12];
    int p1 = 0;
    Point[] player2 = new Point[12];
    int p2 = 0;
    for (int i = 0; i < 7; i++) {
        for (int j = 0; j < 7; j++) {
            if (board[i][j] == 1) {
                Point p = new Point(i, j);
                player1[p1] = p;
                p1++;
                //System.out.println(p.getX()+ " 1 " + p.getY());
            } else if (board[i][j] == 2) {
                Point p = new Point(i, j);
                player2[p2] = p;
                p2++;
                //System.out.println(p.getX()+ " 2 " + p.getY());
            }
        }
    }
    for(int i1=0;i1<player1.length;i1++) {
        ArrayList<Point> temp = getPossibleMoves(player1[i1]);
        if(temp.isEmpty())
            return true;
    }
    for(int i1=0;i1<player1.length;i1++) {
        ArrayList<Point> temp = getPossibleMoves(player2[i1]);
        if(temp.isEmpty())
            return true;
    }
    return false;
} 

问题是当我运行这些测试时,它们都出现数组索引越界错误 这些是测试

最初:

  @Test(timeout=1000)
public void testGameOverInitial() {
    assertFalse(board.isGameOver());
}

经过一些 Action :

 @Test(timeout=1000)

public void testGameOverAfterSomeMoves() {
    board.move(new Point(1, 0), new Point(3, 2)); // White's turn
    board.move(new Point(0, 5), new Point(2, 5)); // Black's turn
    assertFalse(board.isGameOver());
}

最佳答案

由于 p1p2 嵌套在 for 循环中,因此它们最多可以增加 49,而不是 12(两者的大小)你的玩家数组。

您可以检查 p1 的长度(如果它小于 player1.length),就像@LuiggiMendoza 建议的那样。或者您可以修复循环和 player 数组的长度。

我不确定你想做什么。您需要为您要解决的问题选择最佳解决方案。

关于java - 数组索引越界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244159/

相关文章:

eclipse - 如何在 Eclipse 控制台中发出 Ctrl-C(键盘中断)?

java - 为什么在 Wildfly 8.2.1 中访问 EJB 2.1 时出现 ClassCastException?

android - 创建新的android项目时,出现错误 "Activity Name must be specified"

java - 如何在 ERROR 日志级别模式下运行 mongodb 实例?

java jpa : list and sublist

eclipse - 隐藏 Eclipse 顶部主菜单

java - 如何打印 JTextPane 的内容

java - 提供的 javaHome 似乎无效。我找不到 java 可执行文件。尝试位置 : C:\Program Files\Java\jdk-17\bin\java. exe

Java - 静态和最终变量

java - 对于使用 EO 模型优化查询有什么建议吗?