【问题标题】:Should this be a different data type?这应该是不同的数据类型吗?
【发布时间】:2019-11-03 20:09:01
【问题描述】:

我正在编写一个程序,有人可以在其中添加、标记为完成并添加作业。该程序将所有信息存储在字典中,并将其全部放入文本文件中,这样数据就不会丢失。但是在第 101 行我收到此错误“System.ArgumentNullException:'字符串引用未设置为字符串的实例。 参数名称:s'"。谁能告诉我出了什么问题?

我尝试更改某些内容的数据类型,但仍然没有,并且所有数据都以相同的顺序从文本文件中写入和读取:描述、主题、教师、到期日期、状态。所以我不知道出了什么问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace HomeworkTingaling
{
    class Program
    {
        struct homeworkStruct
        {
            public string subject;
            public string teacher;
            public DateTime dateDue;
            public bool completed;
        }

        static void Main(string[] args)
        {
            Dictionary<string, homeworkStruct> homework = new Dictionary<string, homeworkStruct>();
            int selection = 0;
            bool YorN = true;
            selection = menu(selection);
            //gets a selection from the menu method then decides which methods to use depending on the users input
            while (YorN == true)
            {
                if (selection == 1)
                {
                    //get the homework, display it and then display the menu
                    homework = getHomework(homework);
                    displayHomework(homework);
                    Console.WriteLine("\n\n");
                    System.Threading.Thread.Sleep(1000);
                    dictToTxt(homework);
                    menu(selection);                   
                }
                if(selection == 2)
                {
                    homework = getHomework(homework);
                    completeHomework(homework);
                    System.Threading.Thread.Sleep(1000);
                    dictToTxt(homework);
                    menu(selection);
                }
                if(selection == 3)
                {
                    homework = getHomework(homework);
                    addHomework(homework);
                    System.Threading.Thread.Sleep(1000);
                    dictToTxt(homework);
                    menu(selection);
                }
                if (selection == 4)
                {
                    Console.WriteLine("Goodybe!");
                    YorN = true;
                }
            }
        }

        //menu method
        static int menu(int selection)
        {
            selection = 0;
            bool YorN = true;
            //loop continues until a valid number is entered, at which point it breaks the loop and passes the input to the main 
            while (YorN == true)
            {
                Console.WriteLine("Please enter a number that corresponds with what you would like to do: ");
                Console.WriteLine("----------------------------------------\n1. View homework\n2. Complete Homework\n3. Add Homework\n4. Exit\n----------------------------------------");
                selection = int.Parse(Console.ReadLine());
                if (selection < 1 || selection > 4)
                {
                    Console.WriteLine("Invalid number selection!");
                    System.Threading.Thread.Sleep(500);
                }
                else
                {
                    YorN = false;
                }
            }
            return selection;
        }

        //getHomework method
        static Dictionary<string, homeworkStruct> getHomework(Dictionary<string, homeworkStruct> homework)
        {
            //FILE NOT OPENING
            StreamReader homeworkReader = new StreamReader(@"C:\Users\User\source\repos\HomeworkTIngaling\HomeworkTIngaling\bin\Debug\homework.txt", true);
            while (!homeworkReader.EndOfStream)
            {
                //convert to the correct datatypes in the order or the txt file, then add to homework array
                string name = homeworkReader.ReadLine();
                homeworkStruct thishomework;

                thishomework.subject = homeworkReader.ReadLine();
                thishomework.teacher = homeworkReader.ReadLine();
                thishomework.dateDue = DateTime.Parse(homeworkReader.ReadLine());
                thishomework.completed = bool.Parse(homeworkReader.ReadLine());
                homework.Add(name, thishomework);               
            }
            homeworkReader.Close();
            return homework;
        }

        //display homework
        static void displayHomework(Dictionary<string, homeworkStruct> homework)
        {
            foreach (KeyValuePair<string, homeworkStruct> item in homework)
            {
                if (item.Value.completed == false)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Homework: {1}  Subject: {2}  Teacher: {3}  Due Date: {4}  Status: {5}", item.Key, item.Value.subject, item.Value.teacher, item.Value.dateDue, item.Value.completed);
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Homework: {1}  Subject: {2}  Teacher: {3}  Due Date: {4}  Status: {5}", item.Key, item.Value.subject, item.Value.teacher, item.Value.dateDue, item.Value.completed);
                }
            }
        }

        //turning dictionary to text file
        static Dictionary<string, homeworkStruct> dictToTxt(Dictionary<string, homeworkStruct> homework)
        {            
            StreamWriter dictToText = new StreamWriter(@"C:\Users\User\source\repos\HomeworkTIngaling\HomeworkTIngaling\bin\Debug\homework.txt", true);
            //adds each item into the homework dictionary
            foreach (KeyValuePair<string, homeworkStruct> item in homework)
            {
                dictToText.WriteLine(item.Key);
                dictToText.WriteLine(item.Value.subject);
                dictToText.WriteLine(item.Value.teacher);
                dictToText.WriteLine(item.Value.dateDue);
                dictToText.WriteLine(item.Value.completed);
                dictToText.WriteLine("");
            }
            dictToText.Close();
            return homework;
        }

        //mark homework as completed
        static Dictionary<string, homeworkStruct> completeHomework(Dictionary<string, homeworkStruct> homework)
        {
            bool YorN = true;
            //displaying the homework so they can look at the description of the homework which they would like to mark as complete
            displayHomework(homework);
            Console.WriteLine("Please enter the name of the homework you would like to mark as complete: ");
            string selection;
            //look through the dictionary until the correct homework is found, if not found, run again
            while (YorN == true)
            {
                selection = Console.ReadLine();
                foreach (KeyValuePair<string, homeworkStruct> item in homework)
                {
                    if (item.Key == selection)
                    {
                        Console.WriteLine("The homework", Console.ForegroundColor = ConsoleColor.Yellow, "{0} has been marked as complete!", item.Key);
                        if (item.Value.completed == true)
                        {
                            break;
                        }
                        else
                        {
                            //CHANGE BOOL 'COMPLETED' TO TRUE
                        }
                        YorN = false;
                    }                    
                }
                if (YorN == true)
                {           
                    Console.WriteLine("Please enter a valid homework description: ");                    
                }
            }
            return homework;
        }
        //addHomework method
        static Dictionary<string, homeworkStruct> addHomework(Dictionary<string, homeworkStruct> homework)
        {
            bool YorN = true;
            //getting input from user (entering all individual details)
            Console.WriteLine("Describe the homework: ");
            string description = Console.ReadLine();
            Console.WriteLine("What subject is this for? ");
            string subject = Console.ReadLine();
            Console.WriteLine("What is the name of the teacher? ");
            string teacher = Console.ReadLine();
            Console.WriteLine("What date is this homework due in for? ");
            DateTime dateDue = DateTime.Parse(Console.ReadLine());
            Console.WriteLine("Is this homework completed? (Please enter a 'y' for yes or a 'n' for no)");
            string status;
            bool complete = true;
            //only continue when the question is answered
            while (YorN == true)
            {
                status = Console.ReadLine();
                if (status == "y")
                {
                    complete = true;
                    YorN = false;
                }
                if (status == "n")
                {
                    complete = false;
                    YorN = false;
                }
                else
                {
                    Console.WriteLine("Please enter either a 'y' or 'n': ");
                }
            }
            //ready all info for entering into the homework dictionary
            string newHomeworkStrin = description;
            homeworkStruct newHomework;
            newHomework.subject = subject;
            newHomework.teacher = teacher;
            newHomework.dateDue = dateDue;
            newHomework.completed = complete;
            //add all details to homeworks dictionary
            homework.Add(newHomeworkStrin, newHomework);
            //pass back the homework array
            Console.WriteLine("Thank you, your homework has been added!");
            return homework;
        }
    }
}

它让我可以添加信息,这部分工作。这是当前存储在文件中的数据(每一位数据都在一个新行上): “数学学习包6” “数学” “数学先生” “07/01/2020 00:00:00” “真”

这应该会在屏幕上显示为绿色,但第 101 行不断出现错误。

【问题讨论】:

  • 发生这种情况是因为StreamReader.ReadLine() 在到达流的末尾时返回null。然后,您将此 null 值传递给 DateTime.Parse(),这会引发异常,因为它不允许将 null 作为参数。
  • 不确定第 109 行是什么,但是,如果您将 Console.WriteLine 与占位符一起使用,则占位符编号以 0 而不是 1 开头。因此,您应该首先拥有{0},然后是{1},最后是{4}
  • @BionicCode 我该如何解决?
  • 您可以使用StreamReader.EndOfStreamStreamReader.Peek() 来检查流是否已到达末尾。或使用DateTime.TryParse(),它允许null 作为参数,但如果参数为null,则返回false
  • @BionicCode 对不起,我是新手,但您能否举例说明我如何在此代码中使用前两个命令?不吃就吃,我自己试试看:)

标签: c# datetime dictionary text-files streamreader


【解决方案1】:

这是因为StreamReader.ReadLine() 在到达流的末尾时返回null。然后,您将此 null 值传递给 DateTime.Parse(),这会引发异常,因为它不允许将 null 作为参数。

您可以使用StreamReader.EndOfStreamStreamReader.Peek() 来检查流是否已结束。或者使用DateTime.TryParse(),它允许null作为参数,但如果参数是null,则返回false:

using (StreamReader homeworkReader = new StreamReader(@"C:\Users\User\source\repos\HomeworkTIngaling\HomeworkTIngaling\bin\Debug\homework.txt", true))
{
  while (!homeworkReader.EndOfStream)
  {
    string name = homeworkReader.ReadLine();
    homeworkStruct thishomework;

    thishomework.subject = homeworkReader.ReadLine() ?? string.Empty;

    thishomework.teacher = homeworkReader.ReadLine() ?? string.Empty;

    thishomework.dateDue = DateTime.TryParse(homeworkReader.ReadLine(), out DateTime dueDate) 
      ? dueDate
      : DateTime.Now;

    thishomework.completed = bool.TryParse(homeworkReader.ReadLine(), out bool isCompleted)
      ? isCompleted
      : false;        

    if (!homework.Contains(name))
    {
      homework.Add(name, thishomework);    
    }    
  }
}

【讨论】:

  • 我已经尝试过实现它,但是现在程序并不总是具有日期的值,因此 thishomewowrk" 并不总是被分配并且不能添加到作业中。我该怎么办那个?
  • 您的文件格式错误,缺少日期,或者您需要提供默认的DateTime 作为备用值。我会更新我的答案。
  • 如果缺少日期(或任何其他数据),您可以考虑忽略数据集,因为它不完整,因此可以评估为无效。您可以忽略此记录。
  • 程序仍然在 "homework.add(name, thishomework)" 行上大惊小怪,因为并非所有值都必须总是分配
  • 是的,所以你决定保留作业,尽管他们的数据不完整?然后按照我之前说的做:在丢失数据的情况下分配默认值。我给你看。
猜你喜欢
  • 1970-01-01
  • 2014-11-12
  • 2011-03-26
  • 2010-11-23
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2012-02-20
相关资源
最近更新 更多