Java Reference
In-Depth Information
If commandWord is made to be of type CommandWord rather than String , then this can be
rewritten as:
if(commandWord == CommandWord.UNKNOWN) {
System.out.println("I don't know what you mean...");
else if(commandWord == CommandWord.HELP) {
else if(commandWord == CommandWord.GO) {
else if(commandWord == CommandWord.QUIT) {
wantToQuit = quit(command);
In fact, now that we changed the type to CommandWord , we could also use a switch statement instead
of the series of if statements. This expresses the intent of this code segment a little more clearly. 2
switch (commandWord) {
System.out.println("I don't know what you mean...");
case HELP:
case GO:
case QUIT:
wantToQuit = quit(command);
The switch statement takes the variable in the parentheses following the switch keyword
( commandWord in our case) and compares it to each of the values listed after the case key-
words. When a case matches, the code following it is executed. The break statement causes the
switch statement to abort at that point, and execution continues after the switch statement. For a
fuller description of the switch statement, see Appendix D.
A switch
statement selects
a sequence of
statements for
execution from
multiple different
Now we just have to arrange for the user's typed commands to be mapped to the corresponding
CommandWord values. Open the zuul-with-enums-v1 project to see how we have done this. The most
significant change can be found in the CommandWords class. Instead of using an array of strings to
define the valid commands, we now use a map between strings and CommandWord objects:
public CommandWords()
validCommands = new HashMap<String, CommandWord>();
validCommands.put("go", CommandWord.GO);
2 As of Java 7, strings can also be used as values in switch statements. In Java 6 and earlier, strings cannot
be used in switch statements.
Search WWH ::

Custom Search