C#, lesson 15
Time to put it all together. Real programs are rarely one clever trick; they are many ordinary pieces arranged clearly. This lesson has two projects. Each one reads a stream of commands or records, keeps some state, and prints a report.
Answer four questions first:
Then build in layers and run the program after each one: parse a line, update the state, print the report.
A command processor stays readable when every line takes the same path:
The case ["add", var name, var qty] lines are : they match an array with
exactly that shape and pull the pieces into variables, so a line with missing or extra parts falls
through to . Helper methods such as each do one job and throw an exception when a
rule is broken. is the single place that turns exceptions into messages.
2 exercises to try what you just read.
defaultAddProcessNote that this Process is not static: it is a local function that uses variables from the
surrounding top-level code, such as the stock dictionary. Non-static local functions can do that.
Give each stock item its own small class with a private setter for the quantity and methods such
as Remove(int qty) that enforce "you cannot sell more than you have". When the rules live in the
class, the rest of the program cannot break them by accident.
For the report, a SortedDictionary<string, Item> created with StringComparer.Ordinal keeps
items in a predictable alphabetical order without extra sorting.
Use decimal for prices and revenue, and format with F2. Unlike double, it adds up cents
exactly.
Run the sample first, then try what could go wrong: empty input, an unknown item, selling exactly the remaining stock, two students with the same average. The hidden tests check cases like these.
Process one command per line:
| Command | Effect and output |
|---|---|
add <item> <qty> <price> | Adds qty units to the item (creating it if new) and sets its unit price. Prints Added <qty> <item>. |
sell <item> <qty> | Sells units. Prints Sold <qty> <item> and adds qty × price to the revenue. |
report | Prints every item in ordinal order of its name as <item>: <qty> @ <price>, then Revenue: <revenue>. Prices and revenue use two decimals. |
Errors, which change nothing:
Error: unknown item <item>Error: only <stock> <item> leftadd or sell: Error: bad quantityError: bad commandBlank lines are ignored. Items that sell out stay in the report with quantity 0.
Sample input:
Sample output:
Each input line is <student> <score>, where the score is a whole number from 0 to 100. A
student can appear on many lines. Blank lines are ignored, and there is at least one score.
Print one line per student, in ordinal order of their names:
<student>: average <avg> grade <letter>, where the average has one decimal place and the letter
is A for an average of 90 or more, B for 80 or more, C for 70 or more, D for 60 or more,
and F otherwise. Then print Class average: <avg> (the average of all scores, one decimal)
and Top student: <name> (highest average; if several tie, the first in ordinal order).
Model each student with a small class that collects scores and computes its own average. LINQ's
Average and MaxBy are welcome.
Sample input:
Sample output:
void Process(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
try
{
switch (parts)
{
case ["add", var name, var qty]:
Add(name, int.Parse(qty)); // FormatException if qty is not a number
break;
case ["report"]:
Report();
break;
default:
throw new FormatException();
}
}
catch (FormatException)
{
Console.WriteLine("Error: bad command");
}
catch (InventoryException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}add apple 10 0.50
add pear 5 0.80
sell apple 4
sell pear 9
sell kiwi 1
add apple 2 0.60
reportAdded 10 apple
Added 5 pear
Sold 4 apple
Error: only 5 pear left
Error: unknown item kiwi
Added 2 apple
apple: 8 @ 0.60
pear: 5 @ 0.80
Revenue: 2.00mia 90
leo 72
mia 85
ana 64
leo 80ana: average 64.0 grade D
leo: average 76.0 grade C
mia: average 87.5 grade B
Class average: 78.2
Top student: mia