Skip to content

Commit 6fc4ce2

Browse files
committed
Add EnumDemoWithUserInput
1 parent 9708324 commit 6fc4ce2

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.Scanner;
2+
3+
public class EnumDemoWithUserInput {
4+
5+
public static void main(String[] args) {
6+
7+
ComputerType myComputerType = null;
8+
9+
Scanner scanner = new Scanner(System.in);
10+
11+
// prompt the user
12+
System.out.print("Enter computer type (SMARTPHONE, TABLET, LAPTOP, DESKTOP): ");
13+
String userInput = scanner.nextLine().trim().toUpperCase();
14+
15+
// convert string to enum
16+
try {
17+
myComputerType = ComputerType.valueOf(userInput);
18+
System.out.println("You selected: " + myComputerType);
19+
}
20+
catch (IllegalArgumentException exc) {
21+
System.out.println("Invalid computer type entered: " + userInput);
22+
System.exit(1);
23+
}
24+
finally {
25+
scanner.close();
26+
}
27+
28+
String description = switch (myComputerType) {
29+
case ComputerType.SMARTPHONE -> "Smart phones offer computing power in your hand.";
30+
case ComputerType.TABLET -> "Tablets are lightweight for browing and light tasks.";
31+
case ComputerType.LAPTOP -> "Laptops are portable for work on the go.";
32+
case ComputerType.DESKTOP -> "Desktops excel in gaming and work related tasks.";
33+
default -> "Unknown computer type.";
34+
};
35+
36+
System.out.println(description);
37+
}
38+
}

0 commit comments

Comments
 (0)