Programming and Problem Solving with Java

(やまだぃちぅ) #1
9.2 Additional Control Statements | 441

case'D' :
case'F' : outFile.print("Poor Work");
numberInTrouble++;
break; // Unnecessary, but a good habit
}


Note that the final breakstatement is unnecessary, but programmers often include it any-
way. One reason is that it’s easier to insert another case label at the end if a breakstatement
is already present.
If gradedoes not contain one of the specified characters, none of the statements within
the switchexecutes. It would be wise to add a defaultlabel to account for an invalid grade:


switch(grade)
{
case'A' :
case'B' : outFile.print("Good Work");
break;
case'C' : outFile.print("Average Work");
break;
case'D' :
case'F' : outFile.print("Poor Work");
numberInTrouble++;
break;
default : outFile.print(grade + " is not a valid letter grade.");
}


A switchstatement with a breakstatement after each case alternative behaves exactly
like an if-else-ifcontrol structure. For example, the preceding switchstatement is equivalent
to the following code:


if (grade == 'A' || grade == 'B')
outFile.print("Good Work");
else if(grade == 'C')
outFile.print("Average Work");
else if(grade == 'D' || grade == 'F')
{
outFile.print("Poor Work");
numberInTrouble++;
}
else
outFile.print(grade + "is not a valid letter grade.");


Is either of these two versions better than the other? There is no absolute answer to this
question. In this particular example, the switchstatement is easier to understand because

Free download pdf