【问题标题】:Use the "new" keyword to create an object instance [duplicate]使用“new”关键字创建对象实例[重复]
【发布时间】:2016-11-11 06:36:10
【问题描述】:

是否有人可以帮助我解决以下问题,我正在尝试从输入文件中拆分数据(每行 2 条数据,由下面代码中指定的任何一个分隔符分隔)。为此,我声明了字符串数组“拆分输入”,但是当我运行程序时,我收到运行时错误(screenshot),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);

感谢您的帮助

【问题讨论】:

  • 使用调试,看看你的代码中有什么是空的!我想您的计数
  • ReadLine 调用在 EndOfStream 之前至少返回一次 null。
  • 为什么要查看count &lt; gameArray.Length?计数始终为 0
  • 我没有在消息框行下方添加“count++ line”,因为我想在继续之前查看文件是否正在被读取。我现在添加了它,但我仍然遇到同样的错误。它看起来不像正在读取输入文件。我已经用额外的代码更新了我的原始帖子,这样你就可以看到我将输入文件作为参数传递给方法的位置

标签: c# arrays split


【解决方案1】:

只需在null 上添加检查即可。

如果到达输入流的末尾,ReadLine 方法返回 null。这是可能的,因为您检查了!inputFile.EndOfStreamcount &lt; 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]); 
            }
        }

【讨论】:

  • 这已经消除了错误,但我不明白为什么'rawinput'为空,它应该从我在调用方法时作为参数传递的文本文件中读取?
  • 因为您逐行读取文件,如果它是文件的结尾,它仍然会再读取一行,因为 count &lt; gameArray.Length 已通过
【解决方案2】:

检查 null 而不是流结束。

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

【讨论】:

  • 如果两个非空行之间有一个空行,它不会打破循环吗?在那种情况下,这不是一个合适的解决方案!
猜你喜欢
  • 2023-03-19
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2017-04-05
相关资源
最近更新 更多