'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. getint is a method to get user input while making sure the values are in range
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;
}
Solution 1:[1]
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
row = Math.Max(row,0);
column= Math.Max(column,0);
row = Math.Min(fields.GetUpperBound(0), row);
column= Math.Min(fields.GetUpperBound(1), column);
Solution 2:[2]
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.
Solution 3:[3]
I've added this check at the beginning of the loop which solved my issue:
if (arrLocations[0, 0] == null) break;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Jasvijay |
Solution 3 | estinamir |