【问题标题】:My code always throw exception error我的代码总是抛出异常错误
【发布时间】:2014-06-23 11:39:31
【问题描述】:

您好,我的问题是,当我输入一个大于 7 的值时,它总是抛出异常索引超出范围:必须是非负数或小于集合的大小。参数名称:索引。这是我的代码

List<int> sample = new List<int>();
DataTable dataHolder = new DataTable();
int counter;
int secondCounter;
public Form1()
{
    InitializeComponent();
    Random rnd = new Random();
    for (int i = 0; i <= 100; i++)
    {
        sample.Add(rnd.Next(90, 100));
    }
    dataHolder.Columns.Add("Random Number", typeof(string));
    dataHolder.Columns.Add("Average", typeof(string));
    counter = 0;
    secondCounter = 0;
}

private void button1_Click(object sender, EventArgs e)
{
    List<int> collectionHOlder = new List<int>();

    for (int a = 0; a < 96; a++)
    {
        //if (a != sample.Count)
            for (int i = a; i <= Convert.ToInt32(textBox1.Text) - 1 + a; i++)
            {
                counter++;
                secondCounter++;
                if (i <= 96)
                {
                    collectionHOlder.Add(sample[i]);

                }

                if (secondCounter < Convert.ToInt32(textBox1.Text))
                {
                    dataHolder.Rows.Add(sample[i].ToString(), "");

                }
                if (counter == Convert.ToInt32(textBox1.Text))
                {
                    dataHolder.Rows.Add(sample[i].ToString(), collectionHOlder.Average());
                }

            }
        counter = 0;
        collectionHOlder.Clear();
    }
    dataGridView1.DataSource = dataHolder;

谢谢。

【问题讨论】:

    标签: c#


    【解决方案1】:
    for (int a = 0; a < 96; a++)
    {   
       for (int i = a; i <= Convert.ToInt32(textBox1.Text) - 1 + a; i++)
    

    当输入为 7 且 a 达到 95 时,这变为 7 - 1 + 95 = 101。

    以前,

      for (int i = 0; i <= 100; i++)
      {
         sample.Add(rnd.Next(90, 100));
      }
    

    创建了一个包含 101 个元素的数组,有效位置 0..100

    所以是的,sample[i] 将在 i >= 101 时抛出该异常。


    作为一般建议,请以较小的步骤分解此代码并使用有意义的名称。使调试、查找和修复错误变得更加容易。

    【讨论】:

    • 这段代码总是生成 102 if (i
    【解决方案2】:

    感谢您的所有回答。我现在解决了这个问题,这是我的解决方案

                    **if(i < sample.Count - 1)**
                    if (counter == Convert.ToInt32(textBox1.Text))
                        dataHolder.Rows.Add(sample[i].ToString(), collectionHOlder.Average());
    

    【讨论】:

      猜你喜欢
      • 2013-08-08
      • 2012-08-23
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 2013-04-04
      相关资源
      最近更新 更多