0

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

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

4

3 回答 3

0

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

你应该做

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

之后立马

splitText = text.Split(',');
于 2013-05-21T01:29:32.497 回答
0

问题是,当您将 return 分配text.Split(',')给您时,splitText您正在用一个长度等于拆分text. 在访问特定项目之前,您需要检查数组中现在有多少项目,并且循环可能应该splitText.Length用作上限。

于 2013-05-21T01:30:30.587 回答
0

好吧,当你说:

splitText = text.Split(', ');

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

于 2013-05-21T01:32:24.207 回答