Most of the planner is already written: the two records, the Planner class with IsValid, Add, Complete and Summarize, and the report at the end of Program.cs. Two pieces are missing, and they're the ones that meet the outside world: turning a line of text into a task, and reading every line. You'll write both against the brief you traced in the previous lesson, then compare your version with the finished one.
Warm up: one count for two failures
The reading loop you're about to write has two ways to reject a line: it may not parse, or the planner may be full. One if with || can send both to the same count, because || stops early: when the left side is true, the right side never runs. Predict this small version.
#nullable enable
int rejected = 0;
var stored = new List<string>();
foreach (string? value in new[] { "a", null, "b", "c" })
{
if (value is null || !TryStore(value))
{
rejected++;
}
}
Console.WriteLine($"{stored.Count} stored, {rejected} rejected");
bool TryStore(string value)
{
if (stored.Count >= 2)
{
return false;
}
stored.Add(value);
return true;
}Check your prediction
2 stored, 2 rejectedYour turn
Finish the planner
The workspace has two files. Complete the two places marked TODO:
Planner.ParseTask(string line)inPlanner.csreturns aStudyTaskfor a valid line, andnullfor anything else. Split the line into at most three parts, so the title can contain spaces. The minutes must be a whole number and the flag exactly0or1. Trim the title, build the task, and return it only ifIsValidaccepts it, so the length rules live in one place.- The input loop in
Program.csreads lines untilConsole.ReadLinereturnsnull. Each line goes toPlanner.ParseTaskand then toplanner.Add. A line that fails to parse, or thatAddrefuses because the planner is full, adds 1 torejected, and the loop carries on.
ParseTask is called as Planner.ParseTask(line), on the class name, because it's static: it needs no particular planner, only the text (Day 5 explained the difference). With the input box's four lines, the program prints the report you traced by hand:
Todo: Read chapter (25 min)
Done: Review notes (10 min)
Todo: Practice (180 min)
Tasks: 3
Planned: 215 minutes
Completed: 10 minutes
Remaining: 205 minutes
Rejected: 1Then change the input and try a line of 181 minutes, an empty line, and a title of exactly 40 characters.
Hint 1: the idea
Each step of ParseTask can fail, and each failure has the same answer: return null straight away. Check the cheap things in order (how many parts, a number, a flag) so that by the last line every part is known to be good. The loop needs only one if, because "didn't parse" and "wasn't added" both mean "rejected".
Hint 2: a first step
Start with the loop, using the Day 6 pattern while ((line = Console.ReadLine()) is not null), and count every line as rejected while ParseTask still returns null. You should see Rejected: 4. Then write ParseTask one check at a time and watch the count fall to 1.
Show one solution
// File: Program.cs
#nullable enable
using StudyPlanner;
var planner = new Planner();
int rejected = 0;
string? line;
while ((line = Console.ReadLine()) is not null)
{
StudyTask? parsed = Planner.ParseTask(line);
if (parsed is null || !planner.Add(parsed))
{
rejected++;
}
}
foreach (StudyTask task in planner.Tasks)
{
string state = task.Done ? "Done" : "Todo";
Console.WriteLine($"{state}: {task.Title} ({task.Minutes} min)");
}
Summary summary = planner.Summarize();
Console.WriteLine($"Tasks: {summary.Tasks}");
Console.WriteLine($"Planned: {summary.Planned} minutes");
Console.WriteLine($"Completed: {summary.Completed} minutes");
Console.WriteLine($"Remaining: {summary.Remaining} minutes");
Console.WriteLine($"Rejected: {rejected}");
// File: Planner.cs
#nullable enable
namespace StudyPlanner;
public record StudyTask(string Title, int Minutes, bool Done);
public record Summary(int Tasks, int Planned, int Completed, int Remaining);
public class Planner
{
public const int MaxTasks = 100;
public const int MaxMinutes = 180;
public const int MaxTitleLength = 40;
private readonly List<StudyTask> tasks = new();
public IReadOnlyList<StudyTask> Tasks => tasks;
public static bool IsValid(StudyTask task)
{
return task.Minutes >= 1 && task.Minutes <= MaxMinutes
&& task.Title.Trim().Length >= 1 && task.Title.Trim().Length <= MaxTitleLength;
}
// Returns null for a line that does not describe a valid task.
public static StudyTask? ParseTask(string line)
{
string[] parts = line.Split(' ', 3);
if (parts.Length != 3 || !int.TryParse(parts[0], out int minutes))
{
return null;
}
if (parts[1] != "0" && parts[1] != "1")
{
return null;
}
var task = new StudyTask(parts[2].Trim(), minutes, parts[1] == "1");
return IsValid(task) ? task : null;
}
public bool Add(StudyTask task)
{
if (!IsValid(task) || tasks.Count >= MaxTasks)
{
return false;
}
tasks.Add(task);
return true;
}
public bool Complete(int index)
{
if (index < 0 || index >= tasks.Count)
{
return false;
}
tasks[index] = tasks[index] with { Done = true };
return true;
}
public Summary Summarize()
{
int planned = 0;
int completed = 0;
foreach (StudyTask task in tasks)
{
planned += task.Minutes;
if (task.Done)
{
completed += task.Minutes;
}
}
return new Summary(tasks.Count, planned, completed, planned - completed);
}
}Todo: Read chapter (25 min)
Done: Review notes (10 min)
Todo: Practice (180 min)
Tasks: 3
Planned: 215 minutes
Completed: 10 minutes
Remaining: 205 minutes
Rejected: 1This is the finished planner, the one you can download in a later lesson. ParseTask returns null at the first problem, so the code after each check can trust what it has. It never repeats the length rules; it builds a candidate task and asks IsValid, which Add also calls, so a task can't get into the planner by any path that skips the rules. In the loop, || stops early: if parsed is null, planner.Add(parsed) never runs, and both kinds of failure reach the same rejected++. If yours differs, run both versions on the same input, including the edge cases above, before deciding which is right.
You can run the finished version here too. Compare its output with yours on the same input:
How the pieces fit
Program.cs deals with the outside world. It reads each line, asks the planner to parse and store it, counts rejections, and prints the report. It contains no rules about what makes a task valid.
StudyTask and Summary are records. Each is a line of pure data with value equality, which makes the checks easy to write in the next lesson.
Planner owns the rules. It's a class because it has state that changes, and its list is private, so Add and Complete are the only ways to change it. Tasks is a read-only view.
IsValid is called from both ParseTask and Add. A task built directly in code goes through the same rule as one read from input, so there's no path around it.
Complete uses with to replace the list entry, since a record can't change. Marking a task done twice leaves it done and doesn't count anything twice, because Summarize works out totals from the current tasks each time rather than keeping a running count. That's the same "derived, not stored" idea again.
The constants MaxTasks, MaxMinutes and MaxTitleLength give each limit one name in one place. The 100-task limit also bounds the totals, at most 18,000 minutes, so an int is more than large enough.
Completion is saved in this browser only. It does not measure mastery.