Java Reference
In-Depth Information
Enter an integer: 4
HiEven
Enter an integer:
30
HiFive
HiEven
The program prompts the user to enter an integer (lines 6-7) and displays
HiFive
if it is
divisible by
5
(lines 9-10) and
HiEven
if it is divisible by
2
(lines 12-13).
3.4
✓
✓
Write an
if
statement that assigns
1
to
x
if
y
is greater than
0
.
Check
3.5
Point
Write an
if
statement that increases pay by 3% if
score
is greater than
90
.
An
if-else
statement decides the execution path based on whether the condition is
true or false.
Key
Point
A one-way
if
statement performs an action if the specified condition is
true
. If the condition
is
false
, nothing is done. But what if you want to take alternative actions when the condition
is
false
? You can use a two-way
if-else
statement. The actions that a two-way
if-else
statement specifies differ based on whether the condition is
true
or
false
.
Here is the syntax for a two-way
if-else
statement:
if
(boolean-expression) {
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}
The flowchart of the statement is shown in Figure 3.2.
true
false
boolean-
expression
Statement(s) for the true case
Statement(s) for the false case
F
IGURE
3.2
An
if-else
statement executes statements for the true case if the
Boolean-
expression
evaluates to
true
; otherwise, statements for the false case are executed.
Search WWH ::
Custom Search