Zai*_*ain 20 c# arrays indexing bounds
我知道这个问题是什么,但我对我的程序如何输出一个超出数组的值感到困惑.
我有一个0到8的整数,这意味着它可以保持9个整数,对吗?我有一个int,检查以确保用户输入值是1-9.我从整数中删除一个(像这样)
if (posStatus[intUsersInput-1] == 0) //if pos is empty
{
posStatus[intUsersInput-1] += 1;
}//set it to 1
Run Code Online (Sandbox Code Playgroud)
然后我自己输入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
}
Run Code Online (Sandbox Code Playgroud)
错误:
"Index was outside the bounds of the array." "Index was outside the bounds of the array."
Run Code Online (Sandbox Code Playgroud)
M.S*_*.S. 22
您声明了一个可以存储8个元素而不是9个元素的数组.
this.posStatus = new int[8];
Run Code Online (Sandbox Code Playgroud)
这意味着postStatus将包含索引0到7的8个元素.
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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
266245 次 |
最近记录: |