diff --git a/Crate.java b/Crate.java index 7c87ae1..a213d5c 100644 --- a/Crate.java +++ b/Crate.java @@ -1,3 +1,5 @@ +import java.util.Optional; + public class Crate { private T box1; @@ -22,18 +24,21 @@ public void insertBottle(T bottle, int box) throws CrateIndexOutOfBoundsExceptio } } - public T takeBottle(int box) throws CrateIndexOutOfBoundsException { + public Optional takeBottle(int box) throws CrateIndexOutOfBoundsException { if (box < 1 || box > 6) { throw new CrateIndexOutOfBoundsException(); } - return switch (box) { - case 1 -> box1; - case 2 -> box2; - case 3 -> box3; - case 4 -> box4; - case 5 -> box5; - default -> box6; - }; + T foundBox = + switch (box) { + case 1 -> box1; + case 2 -> box2; + case 3 -> box3; + case 4 -> box4; + case 5 -> box5; + case 6 -> box6; + default -> null; + }; + return Optional.ofNullable(foundBox); } } diff --git a/Exercise.java b/Exercise.java index e4b94c5..643552d 100644 --- a/Exercise.java +++ b/Exercise.java @@ -11,9 +11,15 @@ public static void main(String[] args) { crate.insertBottle(new WineBottle(), 5); crate.insertBottle(new WineBottle(), 6); - if (crate.takeBottle(3) instanceof BeerBottle beerBottle) { - beerBottle.chugALug(); - } + crate + .takeBottle(3) + .ifPresentOrElse( + bottle -> { + if (bottle instanceof BeerBottle beerBottle) { + beerBottle.chugALug(); + } + }, + () -> System.out.println("Gesuchte Flasche ist nicht vorhanden.")); } catch (CrateIndexOutOfBoundsException e) { System.err.println(e.getMessage()); }