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

Java, lesson 15

Final project: inventory and gradebook

Time to put everything together. Real programs are rarely one clever trick; they are many small, 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.

How to plan a program like this

Before typing, answer four questions:

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

Then build it in layers, checking each one: parse a line, then update the state, then print the report.

A useful shape: parse, validate, apply

A command processor stays readable when each line goes through the same steps:

The order of the catch blocks matters here: is a subclass of , so it must be caught first, or the general block would swallow it. Each helper method (, ) does one job and throws an exception when its rules are broken. The method 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.

NumberFormatException
IllegalArgumentException
add
report
process

Keep state in a sorted map

A TreeMap<String, Item> keeps items sorted by name, so the report needs no extra sorting. Each Item is a small class with private fields and methods such as remove(int qty) that enforce their own rules, for example "you cannot sell more than you have". Keeping those rules inside the class means the rest of the program cannot break them by accident.

Rounding and money

This course uses double with printf("%.2f") for simplicity. Production code that handles real money usually stores whole cents in a long or uses java.math.BigDecimal, because binary floating point cannot represent most decimal fractions exactly.

Testing your work

Use the sample input first, then try the awkward cases yourself: an 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

  • Creating classes (dev.java)
  • Catching and handling exceptions (dev.java)
  • Sorted maps (dev.java)
  • TreeMap API

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 alphabetical order 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 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 alphabetical order: <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 alphabetically first).

Model each student with a small class that collects scores and computes its own average.

Sample input:

Sample output:

static void process(String line) {
    String[] parts = line.trim().split("\\s+");
    try {
        switch (parts[0]) {
            case "add" -> add(parts[1], Integer.parseInt(parts[2]));
            case "report" -> report();
            default -> throw new IllegalArgumentException("bad command");
        }
    } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
        System.out.println("Error: bad command");
    } catch (IllegalArgumentException e) {
        System.out.println("Error: " + e.getMessage());
    }
}
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