【问题标题】:Index was outside the bounds of the array - integers索引超出了数组的范围 - 整数
【发布时间】:2012-10-24 15:38:04
【问题描述】:

我刚刚遇到了一个常见的问题,但我不确定为什么会在这种情况下发生。

string s;
int c1, c2, c3, c4;    

private void button2_Click(object sender, EventArgs e)
{
    String number;
    s = textBox1.Text;
    int[] d = s.Select(c => (int)c - (int)'0').ToArray();

    try
    {
        c1 = (4 * d[1] + 10 * d[2] + 9 * d[3] + 2 * d[4] + d[5] + 7 * d[6]) % 11;
        c2 = (7 * d[1] + 8 * d[2] + 7 * d[3] + d[4] + 9 * d[5] + 6 * d[6]) % 11;
        c3 = (9 * d[1] + d[2] + 7 * d[3] + 8 * d[4] + 7 * d[5] + 7 * d[6]) % 11;
        c4 = (d[1] + 2 * d[2] + 9 * d[3] + 10 * d[4] + 4 * d[5] + d[6]) % 11;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    number = d[1]+d[2]+d[3]+d[4]+d[5]+d[6]+c1+c2+c3+c4.ToString();
    textBox2.Text = number;    
}

它将接受第一个TextBox(es) 中的数字。一旦它移动到 catch 部分,它就会弹出错误Index was outside the bounds of the array 有什么明显的我遗漏了吗?还是这对我的程序来说是独一无二的?

【问题讨论】:

  • 数组索引从 0 开始,你从 1 开始。这可能是原因吗?

标签: c# arrays winforms indexing


【解决方案1】:

我相信您认为您的数组从 1 变为 6。 它从 0 到 5。

【讨论】:

    【解决方案2】:

    您应该确保您的TextBox 包含至少 6 个字符 否则它会给出异常:

    if(textBox1.Text.Length >= 6)
    {
       //your code here
    }
    else
       MessageBox.Show("You must insert at least 6 characters");
    

    然后记住数组的索引是从0而不是1开始的

    【讨论】:

      【解决方案3】:

      输入字符串s = textBox1.Text; 中有多少个字符? 您不对用户输入执行任何检查。

      例如

      textBox1.Text = "1234"; // only 4 digits
      

      然后,当您尝试使用索引 4/5/6 时,您会收到错误消息。
      当然,您还应该考虑数组索引从零开始而不是从一开始。
      在我上面的输入中,您将只有从 0 到 3 的索引。

      一个简单的检查应该是(假设您已经通过其他方式排除了非数字数据)

      s = textBox1.Text;
      if(s.Length != 6)
          MessageBox.Show("6 digits required!");
      else
          .......
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-19
        • 1970-01-01
        • 2015-11-06
        • 2010-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多