Java Reference
In-Depth Information
Sample Run 3:
Enter the test score: 75
The grade is C.
The grade is B.
The grade is A.
Invalid test score.
From these sample runs, it follows that if the value of testScore is less than 0 or greater
than 100 , the program produces correct results, but if the value of testScore is between
0 and 100 , say 75 , the program produces incorrect results. Can you see why?
As in Sample Run 3, suppose that the value of testScore is 75 .Then testScore % 10 = 7 ,
and this value matched the case label 7 . So as we indented, it should print The grade is C .
However, the output is:
The grade is C.
The grade is B.
The grade is A.
Invalid test score.
But why? Clearly, at most, only one println statement is associated with each case
label. The problem is a result of having only a partial understanding of how the switch
structure works. As we can see, the switch statement does not include any break
statement. Therefore, after executing the statement(s) associated with the matching case
label, execution continues with the statement(s) associated with the next case label,
resulting in the printing of four unintended lines.
To output results correctly, the switch structure must include a break statement after
each println statement, except the last println statement. We leave it as an exercise
for you to modify this program so that it outputs correct results.
Once again, we can see that a partially understood concept can lead to serious errors in a
program. Therefore, taking the time to understand each concept and technique com-
pletely will save you hours of debugging time.
4
PROGRAMMING EXAMPLE: Cable Company Billing
This programming example demonstrates a program that calculates a customer's bill
for a local cable company. There are two types of customers: residential and business.
There are two rates for calculating a cable bill: one for residential customers and one
for business customers.
For residential customers, the following rates apply:
￿ Bill-processing fee: $4.50
￿ Basic service fee: $20.50
Search WWH ::




Custom Search