From 90dfab344b91f11e965bf0dff98bf2d6f62296bc Mon Sep 17 00:00:00 2001 From: SteffenLm <33038091+SteffenLm@users.noreply.github.com> Date: Fri, 6 Jun 2025 22:45:32 +0200 Subject: [PATCH 1/2] Solution Optionals 03 --- Crate.java | 10 +++++++--- Exercise.java | 11 ++++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Crate.java b/Crate.java index 7c87ae1..5770779 100644 --- a/Crate.java +++ b/Crate.java @@ -1,3 +1,5 @@ +import java.util.Optional; + public class Crate { private T box1; @@ -22,18 +24,20 @@ 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) { + T foundBox = switch (box) { case 1 -> box1; case 2 -> box2; case 3 -> box3; case 4 -> box4; case 5 -> box5; - default -> box6; + case 6 -> box6; + default -> null; }; + return Optional.ofNullable(foundBox); } } diff --git a/Exercise.java b/Exercise.java index e4b94c5..a273781 100644 --- a/Exercise.java +++ b/Exercise.java @@ -11,9 +11,14 @@ 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()); } From c8a546ed43bb7f8e70faa5ffc0f9d8d08151235c Mon Sep 17 00:00:00 2001 From: github-actions <> Date: Fri, 6 Jun 2025 20:46:02 +0000 Subject: [PATCH 2/2] Google Java Format --- Crate.java | 19 ++++++++++--------- Exercise.java | 3 ++- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/Crate.java b/Crate.java index 5770779..a213d5c 100644 --- a/Crate.java +++ b/Crate.java @@ -29,15 +29,16 @@ public Optional takeBottle(int box) throws CrateIndexOutOfBoundsException { throw new CrateIndexOutOfBoundsException(); } - T foundBox = switch (box) { - case 1 -> box1; - case 2 -> box2; - case 3 -> box3; - case 4 -> box4; - case 5 -> box5; - case 6 -> box6; - default -> null; - }; + 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 a273781..643552d 100644 --- a/Exercise.java +++ b/Exercise.java @@ -11,7 +11,8 @@ public static void main(String[] args) { crate.insertBottle(new WineBottle(), 5); crate.insertBottle(new WineBottle(), 6); - crate.takeBottle(3) + crate + .takeBottle(3) .ifPresentOrElse( bottle -> { if (bottle instanceof BeerBottle beerBottle) {