From 28ec01ea9f96d883fb9fd0652e25a3a1748ef1ad Mon Sep 17 00:00:00 2001 From: Daniel Bulant Date: Thu, 27 Nov 2025 19:44:12 +0100 Subject: [PATCH] add base gearbox --- week13/Gearbox.java | 17 +++++++++++++++++ week13/doc.typ | 6 ++++-- 2 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 week13/Gearbox.java diff --git a/week13/Gearbox.java b/week13/Gearbox.java new file mode 100644 index 0000000..45a2fcb --- /dev/null +++ b/week13/Gearbox.java @@ -0,0 +1,17 @@ +package week13; + +public class Gearbox { + private int gear = 1; + + public static class IllegalGearChangeException extends RuntimeException {} + + void changeGear(int newGear) { + if(newGear == gear) return; + if(newGear != -1 && (newGear < 1 || newGear > 5)) throw new IllegalArgumentException(); + // newGear is now either -1 or 1..=5 + var gearToCheck = newGear; + if(gearToCheck == -1) gearToCheck++; + if(Math.abs(gear - newGear) != 1) throw new IllegalGearChangeException(); + gear = newGear; + } +} diff --git a/week13/doc.typ b/week13/doc.typ index c62b46b..128c5f1 100644 --- a/week13/doc.typ +++ b/week13/doc.typ @@ -21,11 +21,11 @@ For each of the following exceptions, mark whether it is a checked or unchecked: - `ArrayIndexOutOfBoundsException` - unchecked - `NumberFormatException` - unchecked - `ConcurrentModificationException` - unchecked - - `InterruptedException` - unchecked + - `InterruptedException` - checked How many of these have you experienced? -All of these except ConcurrentModificationException as I didn't write multithreaded programs in Java. +Most of these, except the last two as I haven't written threaded programs in java yet. == Exercise 13.07 @@ -34,6 +34,8 @@ Write a class to represent a gearbox with five gears and a gear for reverse. Add a. when switching from any gear other than the first gear into reverse (and vice versa), and b. when skipping one or more gears. For example, it is illegal to switch directly from the first gear to the third gear. It is also not allowed to switch directly from reverse to the fourth gear. +#embedClass(name: "Gearbox") + == Exercise 13.09 Write a class to represent a printer from hell. The class should have a single method `print()`. Whenever this method is called, the printer randomly throws one of the following exceptions: `OutOfPaperException`, `OutOfTonerException`, `PaperJamException`. Write classes for these exceptions. Write a main method, which calls `print()`, catches any exception, prompts the user to take action (e.g. "replace toner"), waits for confirmation from the user, and then calls `print()` again. Bonus points for infuriating or vaguely worded instructions.