Java Reference
In-Depth Information
Display 6.15
The Method values (part 2 of 2)
Sample Dialogue
Enter hours worked for MONDAY
8
Enter hours worked for TUESDAY
8
Enter hours worked for WEDNESDAY
8
Enter hours worked for THURSDAY
8
Enter hours worked for FRIDAY
7,5
Total hours worked = 39.5
TIP: Enumerated Types in switch Statements
You can use an enumerated type to control a switch statement. In other words, the
type of the controlling expression in a switch statement can be an enumerated type.
This is illustrated in Display 6.16. Note that the case labels must be unqualified
names; you use VANILLA , not Flavor.VANILLA .
This program uses the static method valueOf to convert an input string to a value of
the enumerated type. For example,
Flavor.valueOf("STRAWBERRY")
returns Flavor.STRAWBERRY . Note that the program changes the input to all uppercase
letters before giving it as an argument to the method valueOf . The method valueOf
requires an exact match. An invocation of Flavor.valueOf("Vanilla") will end your
program with an error message; 5 you must use "VANILLA" to match the exact spelling
(including upper- versus lowercase) of the value in Flavor .
At this point, you may wonder what the difference is between STRAWBERRY and
Flavor.STRAWBERRY and how to tell which one to use in a given situation. The value of
the enumerated type is STRAWBERRY . We write Flavor.STRAWBERRY to say we mean
STRAWBERRY as defined in Flavor , as opposed to STRAWBERRY as defined in some other
type, such as
enum Berry {STRAWBERRY. BLUEBERRY, RASPBERRY};
5
5 After you cover exceptions in Chapter 9, you will be able to cope with answers like PISTACHIO which
do not correspond to any value of type Flavor . An invocation of Flavor.valueOf("PISTACHIO") , will
throw an IlllegalArgumentException , something explained in Chapter 9. Until then, your program will
simply give an error message when valueOf cannot cope with its argument.
 
Search WWH ::




Custom Search