forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTanks.java
More file actions
47 lines (43 loc) · 1.28 KB
/
Tanks.java
File metadata and controls
47 lines (43 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// enumerations/Tanks.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Preview in JDK 17
// Compile with javac flags:
// --enable-preview --source 17
// Run with java flag: --enable-preview
import java.util.*;
enum Type { TOXIC, FLAMMABLE, NEUTRAL }
record Level(int percent) {
Level {
if(percent < 0 || percent > 100)
throw new IndexOutOfBoundsException(
percent + " percent");
}
}
record Tank(Type type, Level level) {}
public class Tanks {
static String check(Tank tank) {
return switch(tank) {
case Tank t && t.type() == Type.TOXIC
-> "Toxic: " + t;
case Tank t && ( // [1]
t.type() == Type.TOXIC &&
t.level().percent() < 50
) -> "Toxic, low: " + t;
case Tank t && t.type() == Type.FLAMMABLE
-> "Flammable: " + t;
// Equivalent to "default":
case Tank t -> "Other Tank: " + t;
};
}
public static void main(String[] args) {
List.of(
new Tank(Type.TOXIC, new Level(49)),
new Tank(Type.FLAMMABLE, new Level(52)),
new Tank(Type.NEUTRAL, new Level(75))
).forEach(
t -> System.out.println(check(t))
);
}
}