CHAPTER 5 ■ CONTROL FLOW, LOOPING, AND BRANCHING
case 5: {
greeting += "Thursday";
}
case 6: {
greeting += "Friday";
}
case 7: {
greeting += "Saturday";
}
}
greeting += " to you.";
System.out.println(greeting );Listing 5-4 could use a final else statement with no comparison. The final case in Listing 5-6 could
be a default section. Either one works. When I make a single case for every option, I prefer to fill it in,
but that's just a matter of style. As with the final else, you can use a default section either as a shortcut
for all the cases you didn't define or as a way to trap an unexpected value. Only use default as a shortcut
if you're absolutely sure of the values (as we can be when using GregorianCalendar).Looping
Java offers three constructs for looping:- for
- while
- do-while
for loops are the most commonly used, but while and do-while loops certainly have their uses.■ Note All loops have three operations: initialize a variable, test it to see whether we're done, and update the
variable to be tested again. Everything else is just additional detail or alternate syntax, as we see shortly.For Loops
As a rule, use a for loop when you have some value that you can count. For example, whenever you have
an array or a list or an enumeration, you can use a for loop based on the number of items present.
Remember our cardinal direction example from Chapter 3? Let's examine that more closely in
Listing 5-7.