使用“new”;关键字创建对象实例

本文关键字:关键字 创建对象 实例 new 使用 | 更新日期: 2023-09-27 18:17:29

是否有人能够帮助我与以下请,我试图从输入文件拆分数据(每行2块数据,由下面代码中指定的分隔符分开)。为此,我声明了字符串数组"分割输入",但是当我运行程序时,我得到一个运行时错误(截图),while循环内的分割输入行以黄色突出显示。我看不出我做错了什么,我正在复制似乎工作正常的示例代码:(注意:黄色下面的messageBox行只是用于我的测试,以证明分割工作

        private int DetermineArraySize(StreamReader inputFile)
    {
        int count = 0;
        while (!inputFile.EndOfStream)
        {
            inputFile.ReadLine();
            count++;
        }
        return count;
    }
    private void ReadIntoArray(StreamReader inputFile, string[] gameArray, int[] revArray)
    {
        string rawInput;
        string[] splitInput = new string[2];
        int count = 0;
        char[] delimiters = {'=', '@',};
        while (!inputFile.EndOfStream || count < gameArray.Length)
        {
            rawInput = inputFile.ReadLine();
            {
                splitInput = rawInput.Split(delimiters);
                MessageBox.Show(splitInput[0] + " // " + splitInput[1]);
                count++;
            }
        }
    }
    private void rdGameSalesForm_Load(object sender, EventArgs e)
    {
        StreamReader inputFile = File.OpenText("GameSales.txt");    //Open Input File
        int arraySize = DetermineArraySize(inputFile);              //Use input file to determine array size
        string[] gameTitle = new string[arraySize];                 //Declare array for GameTitle
        int[] revenue = new int[arraySize];                         ///Declare array for Revenue
        ReadIntoArray(inputFile, gameTitle, revenue);

谢谢你的帮助

使用“new”;关键字创建对象实例

请在null上添加检查。

ReadLine方法如果到达输入流的末端则返回null。这是可能的,因为你检查了!inputFile.EndOfStreamcount < gameArray.Length。所以在第二个条件中有可能在输入文件读取

时获得null
 while (!inputFile.EndOfStream || count < gameArray.Length)
        {
            rawInput = inputFile.ReadLine();
            if(rawInput !=null)
            {
              splitInput = rawInput.Split(delimiters);
              MessageBox.Show(splitInput[0] + " // " + splitInput[1]); 
            }
        }

检查是否为null而不是流结束

 while((rawInput = Inputfile.ReadLine()) != null)
 {
     splitInput = rawInput.Split(delimiters);
     MessageBox.Show(...);
 }