未处理的异常: System.IndexOutOfRangeException:索引超出了数组的界限(在第一个if语句中)
static int arrayRows = 20;
static int arrayCols = 20;
public void printBoard()
{
int neighbours;
for (y = 0; y < arrayCols; y++)
for (x = 0; x < arrayRows; x++)
{
neighbours = 0;
// Count number of neighbours surrounding live cell
if (parentGen[x-1, y-1] == 1) // top left
neighbours++;
if (parentGen[x-1, y] == 1) // left
neighbours++;
if (parentGen[x-1, y+1] == 1) // bottom left
neighbours++;
if (parentGen[x, y-1] == 1) // middle top
neighbours++;
if (parentGen[x, y+1] == 1) // middle bottom
neighbours++;
if (parentGen[x+1, y-1] == 1) // top right
neighbours++;
if (parentGen[x+1, y] == 1) // right
neighbours++;
if (parentGen[x+1, y+1] == 1) // bottom right
neighbours++;
}
}我能想到的唯一一件事就是我的程序检查坐标< 0?我该如何着手解决这个问题呢?
发布于 2010-09-13 23:20:28
你的第一个坐标是parentGen-1,-1,这将总是抛出异常。
您需要检查您所在的单元格是否在左侧、右侧、顶部或底部有邻居。例如,x=0在左侧没有邻居,y= 20在底部没有邻居。您可能希望将其分解为其他函数,如HasNeighborsLeft(int )等。
编辑:示例代码
if(x > 0 && y > 0 && parentGen[x - 1, y - 1] == 1)
{
neighbors++;
}您可以将此分解到它自己的函数中,例如,您可以将这种逻辑包装在涉及x-1的所有检查周围。
发布于 2010-09-13 23:26:17
您需要对x和y在其范围的顶部和底部进行边界条件检查。您不能合法地使用+1和-1偏移量对整个数组进行索引。将检查分解为x == 0、x == arrayRows-1 (通过不检查此处的无效相对偏移量)的边界条件情况,然后检查x+1和x-1在else中始终有效的情况。与y类似。
发布于 2010-09-13 23:28:24
你的数组从0到>21。同样,您测试的值为-1,-1和22,22您可以通过将for语句链接到
for (int x = 1; x <= arrayCols - 1; x++)
for (int y = 1; y <= arrayRows - 1; y++)此外,循环的问题几乎总是由您始终可以检查的少量情况引起的:
for语句a)开始于比数组更低的下界,或者b)在更高的下界结束a) (int x= -1;b)
在这种情况下,您的问题2。
https://stackoverflow.com/questions/3701767
复制相似问题