Error : Index was outside the bounds of the array.
Solution 1
You have declared an array that can store 8 elements not 9.
this.posStatus = new int[8];
It means postStatus will contain 8 elements from index 0 to 7.
Solution 2
public int[] posStatus;
public UsersInput()
{
//It means postStatus will contain 9 elements from index 0 to 8.
this.posStatus = new int[9];
}
int intUsersInput = 0;
if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8?
{
posStatus[intUsersInput-1] += 1; //set it to 1
}
Solution 3
//if i input 9 it should go to 8?
You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) - array(7).
Related videos on Youtube
Zain
Updated on July 09, 2022Comments
-
Zain almost 2 years
I'm aware of what the issue is stating but I am confused to how my program is outputting a value that's outside of the array..
I have an array of ints which is 0 - 8 which means it can hold 9 ints, correct? I have an int which is checked to make sure the users input value is 1-9. I remove one from the integer (like so)
if (posStatus[intUsersInput-1] == 0) //if pos is empty { posStatus[intUsersInput-1] += 1; }//set it to 1
then I input 9 myself and I get the error. It should access the last int in the array, so I don't see why I'm getting an error. Relevant code:
public int[] posStatus; public UsersInput() { this.posStatus = new int[8]; } int intUsersInput = 0; //this gets try parsed + validated that it's 1-9 if (posStatus[intUsersInput-1] == 0) //if i input 9 it should go to 8? { posStatus[intUsersInput-1] += 1; //set it to 1 }
Error:
"Index was outside the bounds of the array." "Index was outside the bounds of the array."
-
Jon Skeet about 10 yearsIf you want 9 elements, you need
new int[9]
... -
Lee about 10 years
new int[8]
creates an array with 8 elements so the valid indices are [0,7].
-
-
Zain about 10 yearsit says intUsersInput-1 so 9 - 1 = 8 so ti should go to the 8th element?