tom*_*tom 0 c# indexoutofrangeexception
未处理的异常: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++;
}
}
Run Code Online (Sandbox Code Playgroud)
我唯一能想到的是我的程序正在检查坐标<0?我该如何解决这个问题?
你的第一个坐标是parentGen [-1,-1],这将始终抛出异常.
您需要检查您所在的单元格是否具有左侧,右侧,顶部或底部的任何邻居.例如,x = 0左边没有邻居,y = 20左边没有邻居.您可能希望将其分解为其他函数,例如HasNeighborsLeft(int x)等.
编辑:示例代码
if(x > 0 && y > 0 && parentGen[x - 1, y - 1] == 1)
{
neighbors++;
}
Run Code Online (Sandbox Code Playgroud)
您可以将其分解为它自己的函数,并且您可以围绕涉及x-1的所有检查包装这种逻辑.
| 归档时间: |
|
| 查看次数: |
1906 次 |
| 最近记录: |