add base gearbox

This commit is contained in:
Daniel Bulant 2025-11-27 19:44:12 +01:00
parent cc33ed5db7
commit 28ec01ea9f
2 changed files with 21 additions and 2 deletions

17
week13/Gearbox.java Normal file
View file

@ -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;
}
}

View file

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