Java Reference
In-Depth Information
3.30
What is
y
after the following
switch
statement is executed? Rewrite the code using
an
if-else
statement.
x =
3
; y =
3
;
switch
(x +
3
) {
case
6
: y =
1
;
default
: y +=
1
;
}
3.31
What is
x
after the following
if-else
statement is executed? Use a
switch
state-
ment to rewrite it and draw the flowchart for the new
switch
statement.
int
x =
1
, a =
3
;
if
(a ==
1
)
x +=
5
;
else if
(a ==
2
)
x +=
10
;
else if
(a ==
3
)
x +=
16
;
else if
(a ==
4
)
x +=
34
;
3.32
Write a
switch
statement that displays Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, if
day
is
0
,
1
,
2
,
3
,
4
,
5
,
6
, accordingly.
A conditional expression evaluates an expression based on a condition.
You might want to assign a value to a variable that is restricted by certain conditions. For
example, the following statement assigns
1
to
y
if
x
is greater than
0
, and
-1
to
y
if
x
is less
than or equal to
0
.
Key
Point
if
(x >
0
)
y =
1
;
else
y =
-1
;
Alternatively, as in the following example, you can use a conditional expression to achieve
the same result.
y = (x >
0
)?
1
:
-1
;
Conditional expressions are in a completely different style, with no explicit
if
in the state-
ment. The syntax is:
conditional expression
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1
if
boolean-expression
is true;
otherwise the result is
expression2
.
Suppose you want to assign the larger number of variable
num1
and
num2
to
max
. You can
simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
For another example, the following statement displays the message “num is even” if
num
is
even, and otherwise displays “num is odd.”
System.out.println((num %
2
==
0
) ?
"num is even"
:
"num is odd"
);
Search WWH ::
Custom Search