首页 文章

错误:索引超出了数组的范围 . [重复]

提问于
浏览
17

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

我知道这个问题是什么,但我对我的程序如何输出一个超出数组的值感到困惑 .

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

3 回答

  • 6

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

    this.posStatus = new int[8];
    

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

  • 21
    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

    //如果我输入9它应该是8?

    您仍然需要使用数组的元素 . 在循环遍历数组时,您将计算8个元素,但它们仍将是数组(0) - 数组(7) .

相关问题