Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^442) | Exceptions and Additional Control Structures
of its table-like form. When implementing a multiway branching structure, our advice is to
use the one that you feel is easiest to read. Keep in mind that Java provides the switchstate-
ment as a matter of convenience. Don’t feel obligated to use a switchstatement for every mul-
tiway branch.
Finally, let’s look at what happens if we omit the breakstatements inside a switchstate-
ment. Let’s rewrite the preceding code segment as if we forgot to include the breakstatements,
and see how it behaves:
switch(grade) // Wrong version
{
case'A' :
case'B' : outFile.print("Good Work");
case'C' : outFile.print("Average Work");
case'D' :
case'F' : outFile.print("Poor Work");
numberInTrouble++;
default : outFile.print(grade + " is not a valid letter grade.");
}
If gradehappens to be ‘H’, control branches to the statement at the defaultlabel and the
output to the file is
H is not a valid letter grade.
Unfortunately, this case alternative is the only one that works correctly. If gradeis ‘A’, all of
the branches execute and the resulting output is
Good WorkAverage WorkPoor WorkA is not a valid letter grade.
Remember that after a branch is taken to a specific case label, control proceeds sequen-
tially until either abreakstatement or the end of theswitchstatement is encountered. Forgetting
abreakstatement in a case alternative is a very common source of errors in Java code.


The do Statement


The dostatement is a looping control structure in which the loop condition is tested at the
end (bottom) of the loop. This format guarantees that the loop body executes at least once.
The syntax template for the dostatement follows:

As usual in Java, Statement is either a single statement or a block. Also, note that the do

Do-Statement

do
Statement
while ( Expression );
Free download pdf