令人困惑的IndexOutOfBoundsArray异常

时间:2013-05-21 01:25:15

标签: c# arrays indexoutofboundsexception

你们中的任何一个好人都能告诉我可能导致这个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

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

3 个答案:

答案 0 :(得分:0)

每当您阅读少于23个逗号的行时。最有可能的是,这最终是一条空行。

你应该做

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

后立即

splitText = text.Split(',');

答案 1 :(得分:0)

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

答案 2 :(得分:0)

当你说:

splitText = text.Split(', ');

你进一步假设你的循环总是会得到23个元素我怀疑这可能并非总是如此。

相关问题