Я пишу программу, в которую кто-то может добавить, отметить как завершенную и добавить домашнюю работу. Программа сохраняет всю информацию в словаре и помещает все это в текстовый файл, чтобы данные не терялись. Однако в строке 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;
}
}
}
Это позволяет мне добавить информацию, и эта часть работает. Это данные, которые в настоящее время хранятся в файле (каждый бит данных находится в новой строке): «Maths Study Pack 6», «Maths», «Mr.Math», «07/01/2020 00:00:00», «True».
Это должно отображаться зеленым цветом на экране, но в строке 101 появляется ошибка.