数组索引超出范围?
问题描述:
这种方法应该确定游戏是否在最初和经过一些移动之后结束。数组索引超出范围?
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());
}
一些动作后:
@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());
}
答
由于p1
和p2
嵌套在for
循环,他们可以增加到49,而不是12,这是你的两个球员阵列的大小。
您可以检查p1
的长度,如果它小于player1.length
就像@LuiggiMendoza所建议的那样。或者你可以修复你的循环和你的长度,你的数组。
我不知道你在做什么。您需要为您正在尝试解决的问题选择最佳解决方案。
答
您不控制的价值0和p2
变量,所以它们可以大于你的数组长度。
线,或与错误:
player1[p1]
p1++;
player2[p2]
p2++;
一个可能的解决办法是,当你增加这些变量的值来控制:
//similar for player2 and p2
if (p1 < player1.length) {
p1++;
}
错误在哪里?如果我正在阅读这个权利,那么我们将看到其中一个对board [i] [j]'的访问,我们没有看到它被初始化。 – PaulProgrammer 2013-04-26 19:53:50
@PaulProgrammer ArrayIndexOutOfBoundException,如标题所述。 – 2013-04-26 19:55:40
是的,但在哪一行?我的问题是在哪里,不是什么 – PaulProgrammer 2013-04-26 19:56:19