Я поделюсь основной программой и тремя классами ниже:
Код: Выделить всё
using System;
class Program
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please select one of the following choices");
Console.WriteLine("1. Write");
Console.WriteLine("2. Display");
@@ -13,4 +14,65 @@ static void Main(string[] args)
Console.WriteLine("What would you like to do? ");
}
}
}
=======
Journal journal = new Journal();
PromptGenerator promptGenerator = new PromptGenerator();
bool running = true;
while (running)
{
Console.WriteLine("Welcome to the Journal Program! ");
Console.WriteLine("Please select one of the following choices: ");
Console.WriteLine("1. Write");
Console.WriteLine("2. Display");
Console.WriteLine("3. Load");
Console.WriteLine("4. Save");
Console.WriteLine("5. Quit");
Console.Write("What would you like to do? ");
string choice = Console.ReadLine();
switch(choice)
{
case "1":
string prompt = promptGenerator.GetRandomPrompt();
Console.WriteLine(prompt);
string response = Console.ReadLine();
journal.AddEntry(new Entry(prompt, response));
break;
case "2":
journal.DisplayJournal();
break;
case "3":
Console.Write("Enter filename to load: ");
string saveFilename = Console.ReadLine();
journal.SaveJournal(saveFilename);
break;
case "4":
Console.Write("Enter filename to save: ");
string loadFilename = Console.ReadLine();
journal.LoadJournal(loadFilename);
break;
case "5":
running = false;
break;
default:
Console.WriteLine("Invalid option. Please try again.");
break;
}
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
public class Journal
{
private List entries = new List();
public void AddEntry(Entry entry)
{
entries.Add(entry);
}
public void DisplayJournal()
{
foreach (var entry in entries)
{
Console.WriteLine(entry);
}
}
public void SaveJournal(string filename)
{
using (StreamWriter writer = new StreamWriter(filename))
{
foreach (var entry in entries)
{
writer.WriteLine(entry.Date.ToString("o"));
writer.WriteLine(entry.Prompt);
writer.WriteLine(entry.Response);
writer.WriteLine("---");
}
}
}
public void LoadJournal(string filename)
{
entries.Clear();
using (StreamReader reader = new StreamReader(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (DateTime.TryParse(line, out DateTime date))
{
string prompt = reader.ReadLine();
string response = reader.ReadLine();
entries.Add(new Entry(prompt, response) { Date = date });
reader.ReadLine();
}
}
}
}
}
using System;
public class Entry
{
public DateTime Date {get; set; }
public string Prompt {get; set; }
public string Response {get; set; }
public Entry(string prompt, string response)
{
Date = DateTime.Now;
Prompt = prompt;
Response = response;
}
public override string ToString()
{
return $"{Date.ToString("g")}\nPrompt: {Prompt}\nResponse: {Response}\n";
}
}
public class PromptGenerator
{
Подробнее здесь: [url]https://stackoverflow.com/questions/78673553/i-want-to-write-a-program-that-simulates-a-journal-using-c[/url]
Мобильная версия