【问题标题】:Baffling IndexOutOfBoundsArray Exception莫名其妙的 IndexOutOfBoundsArray 异常
【发布时间】:2013-05-21 01:25:14
【问题描述】:

谁能告诉我是什么原因导致这个 C# 方法抛出 IndexOutOfBounds 异常?将不胜感激。

    public bool PopulateStudents(string path)   //decided to return bool if successful reading file.
    {
        theStudentList = new List<Student>(); //create instance..
        string text = null;
        FileInfo source = new FileInfo(@path);
        bool success = true;
        try
        {
            StreamReader r = source.OpenText();
            text = r.ReadLine();
            string[] splitText = new string[23];
            Student currentStudent = new Student();
            while (text != null)
            {
                splitText = text.Split(',');
                currentStudent = new Student(splitText[0], splitText[1], splitText[2]);
                for (int i = 0; i < 20; i += 2)
                {
                    currentStudent.EnterGrade(int.Parse(splitText[i + 3]), int.Parse(splitText[i + 4]));
                }
                currentStudent.CalGrade();
                theStudentList.Add(currentStudent);
                text = r.ReadLine();
            }
            r.Close();
        }
        catch (Exception exc)
        {
            success = false;
            Console.WriteLine(exc.Message);
        }

        return success;

    }

示例输入文件:

0199911,Bill,Gates,27,30,56,60,0,30,83,100,57,60,0,30,59,60,0,30,59,60,88,100
0199912,Steve,Jobs,30,30,55,60,25,30,70,100,55,60,25,30,50,60,0,30,58,60,80,100
0199913,Marc,Andresen,30,30,55,60,25,30,70,100,55,60,25,30,50,60,0,30,58,60,80,100
0199914,Larry,Ellisen,30,30,55,60,25,30,70,100,55,60,25,30,50,60,0,30,58,60,80,100

编辑:您的所有答案都很棒,非常感谢,但事实证明,我的文本文件末尾只有一些空白区域。我想指出,如果我在最后保留空白,您提供的回复将解决此问题。 :)

【问题讨论】:

  • 你能提供一个示例输入文件吗?
  • 请显示哪一行抛出异常。

标签: c# arrays indexoutofboundsexception


【解决方案1】:

每当您阅读少于 23 个逗号的行时。这很可能最后是一个空行。

你应该这样做

if (splitText.Length<24)
{
  WarnLogOrDoSomethingElse(text);
  continue;
}

紧接着

splitText = text.Split(',');

【讨论】:

    【解决方案2】:

    问题在于,当您将text.Split(',') 的返回值分配给splitText 时,您将用一个长度等于拆分text 产生的标记数的数组替换长度为23 的数组。在访问特定项目之前,您需要检查数组中现在有多少项目,并且循环可能应该使用 splitText.Length 作为上限。

    【讨论】:

      【解决方案3】:

      当你说:

      splitText = text.Split(', ');
      

      您进一步假设您总是会得到 23 个元素,我怀疑情况可能并非总是如此。

      【讨论】:

        猜你喜欢
        • 2015-03-19
        • 1970-01-01
        • 2012-05-19
        • 1970-01-01
        • 1970-01-01
        • 2012-03-12
        • 2019-02-04
        • 2013-04-22
        • 1970-01-01
        相关资源
        最近更新 更多