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) {
printHelp();
}
else if(commandWord == CommandWord.GO) {
goRoom(command);
}
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) {
case UNKNOWN:
System.out.println("I don't know what you mean...");
break;
case HELP:
printHelp();
break;
case GO:
goRoom(command);
break;
case QUIT:
wantToQuit = quit(command);
break;
}
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.
Concept:
A
switch
statement
selects
a sequence of
statements for
execution from
multiple different
options.
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