Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions Crate.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import java.util.Optional;

public class Crate<T> {

private T box1;
Expand All @@ -22,18 +24,21 @@ public void insertBottle(T bottle, int box) throws CrateIndexOutOfBoundsExceptio
}
}

public T takeBottle(int box) throws CrateIndexOutOfBoundsException {
public Optional<T> 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);
}
}
12 changes: 9 additions & 3 deletions Exercise.java
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down