加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 错误:索引超出数组的边界.

发布时间:2020-12-15 06:46:56 所属栏目:百科 来源:网络整理
导读:我知道这个问题是在说什么,但是我对我的程序输出一个不在数组中的值感到困惑. 我有一个int数组是0 – 8,这意味着它可以容纳9个int,正确吗? 我有一个int被检查,以确保用户的输入值为1-9.我从整数中删除一个(像这样) if (posStatus[intUsersInput-1] == 0) //
我知道这个问题是在说什么,但是我对我的程序输出一个不在数组中的值感到困惑.

我有一个int数组是0 – 8,这意味着它可以容纳9个int,正确吗?
我有一个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."

解决方法

你已经声明一个数组,可以存储8个元素不是9.
this.posStatus = new int[8];

这意味着postStatus将包含从索引0到7的8个元素.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读