Java, lesson 15
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.
Before typing, answer four questions:
Then build it in layers, checking each one: parse a line, then update the state, then print the report.
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.
NumberFormatExceptionIllegalArgumentExceptionaddreportprocessA 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.
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.
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.
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 alphabetical order 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 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
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