【问题标题】:Error : Index was outside the bounds of the array. [duplicate]错误:索引超出了数组的范围。 [复制]
【发布时间】:2014-03-09 04:21:31
【问题描述】:

我知道问题在说明什么,但我对我的程序如何输出数组之外的值感到困惑..

我有一个 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."

【问题讨论】:

  • 如果你想要9个元素,你需要new int[9]...
  • new int[8] 创建一个包含 8 个元素的数组,因此有效索引为 [0,7]。

标签: c# arrays indexing bounds


【解决方案1】:

//如果我输入9,它应该转到8?

您仍然需要处理数组的元素。遍历数组时,您将计算 8 个元素,但它们仍将是 array(0) - array(7)。

【讨论】:

  • 它说 intUsersInput-1 所以 9 - 1 = 8 所以应该去第 8 个元素?
【解决方案2】:

您声明了一个可以存储 8 个元素而不是 9 个元素的数组。

this.posStatus = new int[8]; 

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

【讨论】:

    【解决方案3】:
    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    
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      相关资源
      最近更新 更多