尝试从文本文件读取时,数组超出索引,以及int32.tryparse

时间:2014-03-06 23:09:27

标签: c# arrays file-io

我收到的错误是说我有一个索引数组,但我不确定我做错了什么。我已经注释掉Visual Studio突出显示的错误行。它发生在ReadData()方法中。谢谢你的任何建议。

  

Lab3.exe中出现'System.IndexOutOfRangeException'类型的第一次机会异常   Lab3.exe中发生了未处理的“System.IndexOutOfRangeException”类型异常   附加信息:索引超出了数组的范围。   程序'[9140] Lab3.vshost.exe:Managed(v4.0.30319)'已退出,代码为0(0x0)。

class Program
{
    private const int MAX_MEDIA_OBJECTS = 100; // Max number of array objects
    private int mediaCount = 0; // Counter to keep track of amount of media in Data.txt

    private Media[] media = new Media[MAX_MEDIA_OBJECTS];

    private Song[] songs = new Song[MAX_MEDIA_OBJECTS];
    private Movie[] movies = new Movie[MAX_MEDIA_OBJECTS];
    private Book[] books = new Book[MAX_MEDIA_OBJECTS];

    static void Main(string[] args)
    {
        Program lab3 = new Program();

        bool didUserExit = false;

        int userSelectedOption;

        lab3.ReadData();

        do // Do While loop for the options menu, exits when the user selects the exit option.
        {
            lab3.DisplayOptions();
            string userInput = Console.ReadLine();

            if (int.TryParse(userInput, out userSelectedOption))
            {
                lab3.ProcessSelectedInput(userSelectedOption, lab3);
            }
            else
            {
                lab3.DisplayErrorMessage();
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();

        } while (!didUserExit);
    }

    public void ReadData()
    {
        // Opens the Data.txt file for read access
        FileStream mediaFile = new FileStream("Data.txt", FileMode.Open, FileAccess.Read);
        StreamReader mediaData = new StreamReader(mediaFile);

        string mediaRow; // Holds each media data per row

        while ((mediaRow = mediaData.ReadLine()) != null)
        {
            // Splits each row with the delimiter
            string[] mediaDataSplit = mediaRow.Split('|');

            // Temporary variables to hold media data
            int year;


            /** ERROR HAPPENS HERE ACCORDING TO VISUAL STUDIO IDE */
            bool didConvert = Int32.TryParse(mediaDataSplit[2].Trim(), out year);

            if (!didConvert)
            {
                Console.WriteLine("Improperly formated field at line {0}", mediaCount + 1);
                Environment.Exit(0);
            }

            if (didConvert)
            {
                Console.WriteLine("trace year {0}", mediaDataSplit[2]);
            }

            mediaCount++;
        }
    }

    public void ProcessSelectedInput(int userSelectedOption, Program labReference)
    {
        switch (userSelectedOption)
        {
            case 1:
                Console.WriteLine("case1");
                break;
            case 2:
                Console.WriteLine("case2");
                break;
            case 3:
                Console.WriteLine("case3");
                break;
            case 4:
                Console.WriteLine("case4");
                break;
            case 5:
                Console.WriteLine("case5");
                break;
            case 6:
                Environment.Exit(0);
                break;
            default:
                labReference.DisplayErrorMessage();
                break;
        }
    }

    public void DisplayOptions()
    {
            Console.Clear();

            Console.WriteLine("1. List All Books");
            Console.WriteLine("2. List All Movies");
            Console.WriteLine("3. List All Songs");
            Console.WriteLine("4. List All Media");
            Console.WriteLine("5. Search All Media by Title");
            Console.WriteLine("");
            Console.WriteLine("6. Exit Program");
            Console.WriteLine("");
            Console.Write("Enter choice: ");
    }

    public void DisplayErrorMessage()
    {
        Console.WriteLine("*** Invalid Choice - Try Again ***");
    }
}

2 个答案:

答案 0 :(得分:4)

错误可能在这里发生:mediaDataSplit[2]

因为你在这里得到它:string[] mediaDataSplit = mediaRow.Split('|');

无论看到什么线都没有那么多“|”你期望的字符,所以当它吐出时不会创建一个大的数组。

你应该检查mediaRow失败时的价值。

答案 1 :(得分:3)

mediaDataSplit包含少于三个元素或者为空。在尝试访问第三个元素之前,您可以检查该元素是否存在:

if(mediaDataSplit.Length >= 3)
    bool didConvert = Int32.TryParse(mediaDataSplit[2].Trim(), out year);