[英]2d array index out of range exception
As soon as i enter the while loop the program throws Index out of range exception, without getting rows and columns value.一旦我进入 while 循环,程序就会抛出 Index out of range 异常,而不会获取行和列的值。 getint is a method to get user input while making sure the values are in range
getint 是一种在确保值在范围内的同时获取用户输入的方法
while(filled>0)
{
row = getint("row: ");
row--;
column = getint("column: ");
column--;
fields[row, column]=getint("value: ");
filled--;
}
edit:编辑:
static int getint(string question)
{
string temp;
int tempint=0;
while (check != 0)
{
check = 0;
Console.Write("\nPlease enter the {0}",question);
temp = Console.ReadLine();
if(!int.TryParse(temp, out tempint))
{
check++;
}
if(question.Length<14 & (tempint<1 | tempint>9))
{
check++;
Console.WriteLine("Invalid Input");
}
}
return tempint;
}
if the code out of bounds can only happen in fields[row, column]
the You can add a check for out of bound of row and column如果代码越界只能发生在
fields[row, column]
您可以添加对行和列越界的检查
row = Math.Max(row,0);
column= Math.Max(column,0);
row = Math.Min(fields.GetUpperBound(0), row);
column= Math.Min(fields.GetUpperBound(1), column);
so, the error was in while loop, i missed the fact that i used global variable "check" and did not reset its value of so when it exit the loop first time its value was set to 0 and hence the exception.所以,错误是在 while 循环中,我错过了这样一个事实,即我使用了全局变量“check”并且没有重置它的值,所以当它第一次退出循环时它的值被设置为 0 并且因此异常。
I've added this check at the beginning of the loop which solved my issue:我在循环的开头添加了此检查,解决了我的问题:
if (arrLocations[0, 0] == null) break;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.