Java Reference
In-Depth Information
do
statement
while
(
condition
);
which can be confusing. A reader may misinterpret the last line—
while(
condition
);
—as
a
while
statement containing an empty statement (the semicolon by itself). Thus, the
do
…
while
statement with one body statement is usually written with braces as follows:
do
{
statement
}
while
(
condition
);
Good Programming Practice 5.2
Always include braces in a
do
…
while
statement. This helps eliminate ambiguity between
the
while
statement and a
do
…
while
statement containing only one statement.
Chapter 4 discussed the
if
single-selection statement and the
if
…
else
double-selection
statement. The
switch
multiple-selection statement
performs different actions based on
the possible values of a
constant integral expression
of type
byte
,
short
,
int
or
char
. As
of Java SE 7, the expression may also be a
String
, which we discuss in Section 5.7.
Using a
switch
Statement to Count A, B, C, D and F Grades
Figure 5.9 calculates the class average of a set of numeric grades entered by the user, and
uses a
switch
statement to determine whether each grade is the equivalent of an A, B, C,
D or F and to increment the appropriate grade counter. The program also displays a sum-
mary of the number of students who received each grade.
Like earlier versions of the class-average program, the
main
method of class
Letter-
Grades
(Fig. 5.9) declares local variables
total
(line 9) and
gradeCounter
(line 10) to
keep track of the sum of the grades entered by the user and the number of grades entered,
respectively. Lines 11-15 declare counter variables for each grade category. Note that the
variables in lines 9-15 are explicitly initialized to
0
.
Method
main
has two key parts. Lines 26-56 read an arbitrary number of integer
grades from the user using sentinel-controlled repetition, update instance variables
total
and
gradeCounter
, and increment an appropriate letter-grade counter for each grade
entered. Lines 59-80 output a report containing the total of all grades entered, the average
of the grades and the number of students who received each letter grade. Let's examine
these parts in more detail.
1
// Fig. 5.9: LetterGrades.java
2
// LetterGrades class uses the switch statement to count letter grades.
3
import
java.util.Scanner;
4
5
public
class
LetterGrades
6
{
7
public
static
void
main(String[] args)
8
{
Fig. 5.9
|
LetterGrades
class uses the
switch
statement to count letter grades. (Part 1 of 3.)