Learn/C#/15. Final project: inventory and gradebook
Lesson 15 of 15
Sign in

C#, lesson 15

Final project: inventory and gradebook

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.

Plan before you type

Answer four questions first:

  1. What does one input line look like, and what can go wrong? Unknown commands, missing parts, text where a number should be.
  2. What state do I keep between lines? Usually a dictionary from a name to an object.
  3. Which types do I need? A class for things whose state changes (stock levels), a record for fixed data, perhaps a small exception class for rule violations.
  4. What exactly does the output look like? Order, decimal places, error messages.

Then build in layers and run the program after each one: parse a line, update the state, print the report.

Parse, validate, apply

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.

Exercise 1

Inventory manager

Press Ctrl Enter or Check to test your code.

Exercise 2

Gradebook

Press Ctrl Enter or Check to test your code.

list patterns
default
Add
Process

Note 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.

Keep the rules inside the class

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.

Money

Use decimal for prices and revenue, and format with F2. Unlike double, it adds up cents exactly.

Test the awkward cases

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.

Further reading

  • Classes
  • List patterns
  • Local functions
  • SortedDictionary<TKey, TValue>

Process one command per line:

CommandEffect 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.
reportPrints 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:

  • selling an item that was never added: Error: unknown item <item>
  • selling more than is in stock: Error: only <stock> <item> left
  • a quantity of zero or less in add or sell: Error: bad quantity
  • an unknown command, missing or extra parts, or numbers that do not parse: Error: bad command

Blank 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
report
Added 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.00
mia 90
leo 72
mia 85
ana 64
leo 80
ana: average 64.0 grade D
leo: average 76.0 grade C
mia: average 87.5 grade B
Class average: 78.2
Top student: mia