试图从文本文件和int32.tryparse读取索引的数组



我遇到的错误说我有一个索引,但我不确定我在做什么错。我已经评论了Visual Studio强调为错误的行。它发生在ReadData()方法中。感谢您的建议。

在lab3.exe中发生了第一个机会" system.indexoutofrangeException"。 在lab3.exe中发生了一个未经处理的例外" system.indexoutofrangeException"。 其他信息:索引不在数组的范围之外。 程序'[9140] lab3.vshost.exe:托管(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 ***");
    }
}

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

由于您在这里获取它的结果:string[] mediaDataSplit = mediaRow.Split('|');

无论它看的哪种行都没有那么多的" |"正如您所期望的那样

您应该检查mediaRow失败时的值是多少。

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

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

最新更新