错误:指数数组的边界之外。 [重复] 错误:指数数组的边界之外。 [重复](Error : I

2019-05-12 04:37发布

这个问题已经在这里有一个答案:

  • 什么是IndexOutOfRangeException / ArgumentOutOfRangeException,如何解决? 4个回答

我知道是什么问题,说明的,但我很困惑,我的计划是如何输出值是这样的阵列外..

我有整数是0的数组 - 8,这意味着它可以容纳9个整数,正确的吗? 我有检查,以确保用户的输入值是1-9的INT。 我从整数去除一个(像这样)

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."

Answer 1:

你已经宣称可以存储8个元素并不9数组。

this.posStatus = new int[8]; 

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



Answer 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    
} 


Answer 3:

//如果我输入9就应该到8?

您还必须与数组中的元素一起工作。 通过数组循环时,你会算8个元素,但他们仍然会是数组(0) - 阵列(7)。



文章来源: Error : Index was outside the bounds of the array. [duplicate]