简体   繁体   中英

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.

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.

You can either check the length of p1 if it is smaller than player1.length like @LuiggiMendoza suggests. Or you can fix your loop and the length of you you player arrays.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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