这应该是其他数据类型吗?

问题描述 投票:0回答:1

我正在编写一个程序,有人可以在该程序中添加,标记为完成并添加作业。该程序将所有信息存储在字典中,并将其全部放入文本文件中,因此数据不会丢失。但是在第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行不断显示错误。

c# datetime dictionary text-files streamreader
1个回答
0
投票

之所以如此,是因为到达流的末尾时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);    
    }    
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.