Java Reference
In-Depth Information
2.2.5 Multiple choices:
switch case
The nested
if else
conditional instructions presented in
2.2.3 are somehow
dicult to use in case one would like to check that a given variable is equal
to such or such a value. Indeed, nested blocks of instructions are dicult to
properly visualize on the screen. In the case of
multiple choices
, it is better
to use the
switch case
structure that branches on the appropriate set of
instructions depending on the value of a given expression. For example, consider
the code:
ยง
class
ProgSwitch
{
public static void
main( String arg [ ] )
{
System . out . print (
"Input a digit in [0..9]:"
);
Scanner keyboard=
new
Scanner(System . in ) ;
int
n=keyboard . nextInt () ;
switch
(n)
case
0: System . out . println (
"zero"
);
break
;
case
1: System . out . println (
"one"
);
break
;
case
2: System . out . println (
"two"
);
break
;
case
3: System . out . println (
"three"
);
break
;
default
:System.out.println(
"Above three!"
);
break
;
}}}
The conditional statement
switch
consider the elementary expression
n
of type
int
and compare it successively with the first case:
case 0
. This means that
if
(n==0)Block1
else
\{
...
\}
. The set of instructions in a
case
should end
with the keyword
break
. Note that there is also the
default
case that contains
the set of instructions to execute when none of the former cases were met. The
formal syntax of the multiple choice
switch case
is thus:
switch
(TypedExpression)
case
C1 :
SetOfInstructions1 ;
break
;
case
C2 :
SetOfInstructions2 ;
break
;
...
case
Cn :
SetOfInstructionsn ;
break
;
default
:
SetOfDefaultInstructions ;
}
}
Search WWH ::
Custom Search