Java Reference
In-Depth Information
TIP: Enumerated Types in
switch
Statements
★
A single program with both type definitions (
Flavor
and
Berry
) could use both
Flavor.STRAWBERRY
and
Berry.STRAWBERRY
.
So, when can you use
STRAWBERRY
instead of
Flavor.STRAWBERRY
? The approximate
answer is that you use
STRAWBERRY
instead of
Flavor.STRAWBERRY
when there is enough
context for the compiler to know
STRAWBERRY
means
STRAWBERRY
as defined in the type
Flavor
. For example, in a
switch
statement, if the type of the controlling expression is
Flavor
, then
STRAWBERRY
can only mean
Flavor.STRAWBERRY
. This rule will help in
remembering when to use
STRAWBERRY
and when to use
Flavor.STRAWBERRY
. But, some-
times you may simply have to check a reference or try the two possibilities out and see
which one (or ones) the compiler accepts.
■
Display 6.16
Enumerated Type in a
switch
Statement
1
import
java.util.Scanner;
2
3
public class
EnumSwitchDemo
4{
5
enum
Flavor {VANILLA, CHOCOLATE, STRAWBERRY};
6
public static void
main(String[] args)
7
{
8
Flavor favorite =
null
;
9
Scanner keyboard =
new
Scanner(System.in);
10
System.out.println("What is your favorite flavor?");
11
String answer = keyboard.next();
12
answer = answer.toUpperCase();
13
favorite = Flavor.valueOf(answer);
The case labels must have just the name of
the value without the type name and dot.
14
switch
(favorite)
15
{
16
case
VANILLA:
17
System.out.println("Classic");
18
break;
19
case
CHOCOLATE:
20
System.out.println("Rich");
21
break;
22
default
:
23
System.out.println("I bet you said STRAWBERRY.");
24
break;
25
}
26
}
27
}