我知道这个问题是什么,但我对我的程序如何输出一个超出数组的值感到困惑。
我有一个0到8的整数数组,这意味着它可以保持9个整数,对吗? 我有一个int,检查以确保用户输入值是1-9。我从整数中删除一个(如此)
if (posStatus[intUsersInput-1] == 0) //if pos is empty
{
posStatus[intUsersInput-1] += 1;
}//set it to 1
然后我自己输入9并得到错误。它应该访问数组中的最后一个int,所以我不明白为什么我会收到错误。 相关代码:
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
}
错误:
"Index was outside the bounds of the array." "Index was outside the bounds of the array."
答案 0 :(得分:22)
您已经声明了一个可以存储8个元素而不是9个元素的数组。
this.posStatus = new int[8];
这意味着postStatus将包含索引0到7的8个元素。
答案 1 :(得分:6)
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
}
答案 2 :(得分:2)
//如果输入9,它应该转到8?
您仍然需要使用数组的元素。在循环遍历数组时,您将计算8个元素,但它们仍将是数组(0) - 数组(7)。