Java Reference
In-Depth Information
LISTING 6.1
continued
case
7:
System.out.println ("average.");
break
;
case
6:
System.out.println ("below average. You should see the");
System.out.println ("instructor to clarify the material "
+ "presented in class.");
break
;
default
:
System.out.println ("not passing.");
}
}
}
OUTPUT
Enter a numeric grade (0 to 100):
86
That grade is above average. Nice job.
In
GradeReport
, the category of the grade is determined by dividing the grade
by 10 using integer division, resulting in an integer value between 0 and 10
(assuming a valid grade is entered). This result is used as the expression of the
switch
, which prints various messages for grades 60 or higher and a default sen-
tence for all other values.
Note that any
switch
statement could be implemented as a set of nested
if
statements. However, nested
if
statements quickly become difficult for a human
reader to understand and are error prone to implement and debug. But because a
switch
can evaluate only equality, sometimes nested
if
statements are necessary.
It depends on the situation.
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 6.1
When a Java program is running, what happens if the expression eval-
uated for a
switch
statement does not match any of the case values
associated with the statement?
SR 6.2
What happens if a case in a
switch
statement does not end with a
break
statement?
SR 6.3
What is the output of the
GradeReport
program if the user enters
“72”? What if the user enters “46”? What if the user enters “123”?
Search WWH ::
Custom Search