Console inventory project
What you will learn
Build a small inventory application with three item IDs. The domain class manages quantities; the command loop translates user text into method calls and reports expected failures.
- Separate console input handling from domain state and validation.
- Verify rejected operations leave stock unchanged and sessions terminate.
Each example is a standalone Main.java. Compile with javac --release 21 Main.java and run with java Main. Java 25 execution remains unverified.
class Inventory { private final int[] stock = new int[3]; private void checkId(int id) { if (id < 0 || id >= stock.length) throw new IllegalArgumentException("Unknown item"); } int count(int id) { checkId(id); return stock[id]; } void add(int id, int quantity) { checkId(id); if (quantity <= 0 || quantity > 100 - stock[id]) throw new IllegalArgumentException("Invalid quantity or capacity"); stock[id] += quantity; } void take(int id, int quantity) { checkId(id); if (quantity <= 0 || quantity > stock[id]) throw new IllegalArgumentException("Insufficient stock or invalid quantity"); stock[id] -= quantity; }}
public class Main { public static void main(String[] args) { Inventory inventory = new Inventory(); inventory.add(0, 5); inventory.take(0, 2); System.out.println(inventory.count(0)); }}Expected output:
3The domain object owns its rules and can be tested independently.
Design the inventory and command boundary
IDs are 0, 1, and 2. Each item starts at zero and has capacity 100. add and take accept positive quantities only; take cannot exceed stock. Validate before mutating, and compare the incoming amount to remaining capacity to avoid overflow. Commands are add ID QUANTITY, take ID QUANTITY, show ID, and quit. A Scanner reads a fixed synthetic transcript, not the live terminal. hasNextLine prevents reading past end of input; the loop processes at most 20 lines. strip removes surrounding whitespace, split with the regular expression \s+ separates words, and parseInt converts integer tokens. The line length check rejects long commands after reading, not a hard memory bound for hostile streams. NumberFormatException is a subclass of IllegalArgumentException, so the specific handler comes first. The domain is intentionally single-threaded and in memory; no database, concurrency or persistence is promised. The project fixture includes an incomplete starter and complete solution.
class Inventory { private final int[] stock = new int[3]; private void checkId(int id) { if (id < 0 || id >= stock.length) throw new IllegalArgumentException("Unknown item"); } int count(int id) { checkId(id); return stock[id]; } void add(int id, int quantity) { checkId(id); if (quantity <= 0 || quantity > 100 - stock[id]) throw new IllegalArgumentException("Invalid quantity or capacity"); stock[id] += quantity; } void take(int id, int quantity) { checkId(id); if (quantity <= 0 || quantity > stock[id]) throw new IllegalArgumentException("Insufficient stock or invalid quantity"); stock[id] -= quantity; }}
public class Main { public static void main(String[] args) { Inventory inventory = new Inventory(); inventory.add(1, 4); try { inventory.take(1, 7); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } System.out.println(inventory.count(1)); }}Expected output:
Insufficient stock or invalid quantity4The check happens before mutation; the failed operation leaves stock intact.
A practical variation
import java.util.Scanner;class Inventory { private final int[] stock = new int[3]; private void checkId(int id) { if (id < 0 || id >= stock.length) throw new IllegalArgumentException("Unknown item"); } int count(int id) { checkId(id); return stock[id]; } void add(int id, int quantity) { checkId(id); if (quantity <= 0 || quantity > 100 - stock[id]) throw new IllegalArgumentException("Invalid quantity or capacity"); stock[id] += quantity; } void take(int id, int quantity) { checkId(id); if (quantity <= 0 || quantity > stock[id]) throw new IllegalArgumentException("Insufficient stock or invalid quantity"); stock[id] -= quantity; }}public class Main { static void run(Scanner input, Inventory inventory) { for (int step = 0; step < 20 && input.hasNextLine(); step++) { String line = input.nextLine(); if (line.length() > 80) { System.out.println("Error: command too long"); continue; } String[] parts = line.strip().split("\\s+"); try { switch (parts[0]) { case "quit" -> { if (parts.length != 1) throw new IllegalArgumentException("Use quit"); return; } case "show" -> { if (parts.length != 2) throw new IllegalArgumentException("Use show ID"); System.out.println("Stock: " + inventory.count(Integer.parseInt(parts[1]))); } case "add", "take" -> { if (parts.length != 3) throw new IllegalArgumentException("Use add/take ID QUANTITY"); int id = Integer.parseInt(parts[1]); int quantity = Integer.parseInt(parts[2]); if (parts[0].equals("add")) inventory.add(id, quantity); else inventory.take(id, quantity); System.out.println("Stock: " + inventory.count(id)); } default -> throw new IllegalArgumentException("Unknown command"); } } catch (NumberFormatException e) { System.out.println("Error: use integer values"); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } } } public static void main(String[] args) { try (Scanner input = new Scanner("add 0 5\ntake 0 2\ntake 0 9\nshow 0\nquit\nadd 0 1\n")) { run(input, new Inventory()); } System.out.println("Session ended"); }}Expected output:
Stock: 5Stock: 3Error: Insufficient stock or invalid quantityStock: 3Session endedThe scripted Scanner provides six lines; quit stops before the last add. The boundary catches expected user errors and keeps the inventory usable.
Common mistakes
Do not update stock first and attempt to undo it after validation. Do not catch every Exception around the entire program: recover expected user errors at the command boundary.
Practice
Extend the project with a total command that displays the sum of all three stock counts, without exposing the internal array. Test empty inventory, multiple items, invalid extra arguments, and quit.
Hints:
- Add a total() method to Inventory using a bounded loop.
- Add a switch branch checking exactly one token; leave all mutation checks intact.
Related reference topics: Java Integer.parseInt(String), Java Scanner.hasNextLine(), Java Scanner.nextLine(). Next: Packages, imports and access boundaries.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Console inventory project — knowledge check
Apply Java exception and inventory contracts using Java 21-compatible examples.
Why separate Inventory from Scanner?
Stock is 99. Is adding 2 allowed?
What happens when take exceeds stock?
Why check token count before indexing?
What limits this session?