ptg7068951
Watching the Clock 87
} else{
numberOfEnemies = 5;
}
A shorter way to do this is to use the ternary operator. Aternary expres-
sion has five parts:
. The condition to test, surrounded by parentheses, as in (skillLevel
- . A question mark (?)
. The value to use if the condition is true
. A colon (:)
. The value to use if the condition is false
To use the ternary operator to set numberOfEnemiesbased on skillLevel,
you could use the following statement:
int numberOfEnemies = (skillLevel > 5)? 10 : 5;
You also can use the ternary operator to determine what information to
display. Consider the example of a program that displays the text “Mr.” or
“Ms.” depending on the value of the gendervariable. Here’s a statement
that accomplishes this:
System.out.print( (gender.equals(“male”))? “Mr.”: “Ms.”);
The ternary operator can be useful, but it’s also the hardest conditional in
Java to understand. As you learn Java, you don’t encounter any situations
where the ternary operator must be used instead of if-elsestatements.
Watching the Clock
The next project gives you another look at each of the conditional tests you
can use in your programs. For this project, you use Java’s built-in time-
keeping feature, which keeps track of the current date and time, and pres-
ent this information in sentence form.
Run NetBeans (or another program to create Java programs) and give a
new class the name Clock. This program is long, but most of it consists of
long conditional statements. Type the full text of Listing 7.3 into the source
code editor, and save the file.