简体   繁体   English

数组索引超出范围?

[英]Array index out of bounds?

This method should determine whether the game is over or not initially and after some moves. 此方法应确定游戏最初是否结束以及是否在某些动作之后。

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

The problem is when i run those tests they both have an error of array index out of bounds Those are the tests 问题是,当我运行这些测试时,他们都有一个数组索引超出界限的错误那些是测试

initially: 原来:

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

after some moves: 经过一些动作:

 @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());
}

You're not controlling the value of p1 and p2 variables, so they can be greater than your array length. 您没有控制p1p2变量的值,因此它们可能大于数组长度。

Lines with the error: 有错误的行:

player1[p1]
p1++;

player2[p2]
p2++;

A possible solution would be to control when you increase the values of these variables: 一种可能的解决方案是控制何时增加这些变量的值:

//similar for player2 and p2
if (p1 < player1.length) {
    p1++;
}

Since p1 and p2 are nested in for loops, they can increase up to 49 instead of 12 that is the size of both of your player arrays. 由于p1p2嵌套在for循环中,因此它们可以增加到49而不是12,这是两个播放器数组的大小。

You can either check the length of p1 if it is smaller than player1.length like @LuiggiMendoza suggests. 你可以检查p1的长度,如果它小于player1.length就像@LuiggiMendoza建议的那样。 Or you can fix your loop and the length of you you player arrays. 或者你可以修复你的循环和player阵列的长度。

I'm not sure what you are trying to do. 我不确定你要做什么。 You need to pick the best solution for the problem you are trying to solve. 您需要为您要解决的问题选择最佳解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM