Skip to content

Commit 90dfab3

Browse files
committed
Solution Optionals 03
1 parent 8930ead commit 90dfab3

2 files changed

Lines changed: 15 additions & 6 deletions

File tree

Crate.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import java.util.Optional;
2+
13
public class Crate<T> {
24

35
private T box1;
@@ -22,18 +24,20 @@ public void insertBottle(T bottle, int box) throws CrateIndexOutOfBoundsExceptio
2224
}
2325
}
2426

25-
public T takeBottle(int box) throws CrateIndexOutOfBoundsException {
27+
public Optional<T> takeBottle(int box) throws CrateIndexOutOfBoundsException {
2628
if (box < 1 || box > 6) {
2729
throw new CrateIndexOutOfBoundsException();
2830
}
2931

30-
return switch (box) {
32+
T foundBox = switch (box) {
3133
case 1 -> box1;
3234
case 2 -> box2;
3335
case 3 -> box3;
3436
case 4 -> box4;
3537
case 5 -> box5;
36-
default -> box6;
38+
case 6 -> box6;
39+
default -> null;
3740
};
41+
return Optional.ofNullable(foundBox);
3842
}
3943
}

Exercise.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,14 @@ public static void main(String[] args) {
1111
crate.insertBottle(new WineBottle(), 5);
1212
crate.insertBottle(new WineBottle(), 6);
1313

14-
if (crate.takeBottle(3) instanceof BeerBottle beerBottle) {
15-
beerBottle.chugALug();
16-
}
14+
crate.takeBottle(3)
15+
.ifPresentOrElse(
16+
bottle -> {
17+
if (bottle instanceof BeerBottle beerBottle) {
18+
beerBottle.chugALug();
19+
}
20+
},
21+
() -> System.out.println("Gesuchte Flasche ist nicht vorhanden."));
1722
} catch (CrateIndexOutOfBoundsException e) {
1823
System.err.println(e.getMessage());
1924
}

0 commit comments

Comments
 (0)