Java Reference
In-Depth Information
a default label, which provides a branch point for the case when there is no
case
label
constant that equates to the
switch
expression value.
The
SwitchTypeChecker isValidSwitchType()
method demonstrates
the use of a
String
as the
switch
test expression. If you study closely the
isVal-
idSwitchType()
method, you will see that it is testing whether a
Class
object
represents a type that corresponds to one of the valid
switch
expression types. The
method also demonstrates how
case
labels can be grouped to implement a logical OR
conditional test. If a
case
label does not have any associated code to execute, and no
break
statement, the flow of execution falls through to the next closest
case
label
containing executable statements, thus allowing common code to be executed if the
result of the
switch
expression matches any one of the grouped
case
constants.
The
RockPaperScissors
class implements a command-line Rock-Paper-Scis-
sors game, where you are playing against the computer. There are two methods in this
class that demonstrate the
switch
statement. The
getHand()
method shows the use
of an
enum
variable in the
switch
expression. The
playHands()
method simply
intends to show that the
switch
expression, although often just a variable, can be any
expression whose result is of one of the allowed
switch
types. In this case, the ex-
pression is using a ternary operator that returns an
int
value.
7-4. Working with Fix-Sized Arrays
Problem
You need a simple data structure that can store a fixed (and possibly large) amount of
same-typed data and provide for fast sequential access.
Solution
Consider using an array. While Java provides more sophisticated and flexible
Col-
lection
types, the array type can be useful data structure for many applications. The
following example demonstrates the simplicity of working with arrays. The
GradeAnalyzer
class provides a means for calculating various grade-related statist-
ics, such as the mean (average) grade, minimum grade, and maximum grade.