Java Reference
In-Depth Information
case
value2: statement(s)2;
break
;
...
case
valueN: statement(s)N;
break
;
default
: statement(s)-
for
-
default
;
}
The
switch
statement observes the following rules:
The
switch-expression
must yield a value of
char
,
byte
,
short
,
int
, or
String
type and must always be enclosed in parentheses. (The
char
and
String
types will be
introduced in the next chapter.)
■
The
value1
, . . ., and
valueN
must have the same data type as the value of the
switch-
expression
. Note that
value1
, . . ., and
valueN
are constant expressions, meaning
that they cannot contain variables, such as
1 + x
.
■
■
When the value in a
case
statement matches the value of the
switch-expression
,
the statements
starting from this case
are executed until either a
break
statement or the
end of the
switch
statement is reached.
■
The
default
case, which is optional, can be used to perform actions when none of the
specified cases matches the
switch-expression
.
■
The keyword
break
is optional. The
break
statement immediately ends the
switch
statement.
Caution
Do not forget to use a
break
statement when one is needed. Once a case is matched,
the statements starting from the matched case are executed until a
break
statement or
the end of the
switch
statement is reached. This is referred to as
fall-through
behavior.
For example, the following code displays
Weekdays
for day of
1
to
5
and
Weekends
for day
0
and
6
.
without
break
fall-through behavior
switch
(day) {
case
1
:
case
2
:
case
3
:
case
4
:
case
5
: System.out.println(
"Weekday"
);
break
;
case
0
:
case
6
: System.out.println(
"Weekend"
);
}
Tip
To avoid programming errors and improve code maintainability, it is a good idea to put
a comment in a case clause if
break
is purposely omitted.
Now let us write a program to find out the Chinese Zodiac sign for a given year. The
Chinese Zodiac is based on a twelve-year cycle, with each year represented by an animal—
monkey, rooster, dog, pig, rat, ox, tiger, rabbit, dragon, snake, horse, or sheep—in this cycle,
as shown in Figure 3.6.
Note that
year % 12
determines the Zodiac sign. 1900 is the year of the rat because
1900
% 12
is
4
. Listing 3.9 gives a program that prompts the user to enter a year and displays the
animal for the year.
Search WWH ::
Custom Search