Java Reference
In-Depth Information
The odds of this code picking a winner are based on the value of the
CHANCE
con-
stant. That is, if
CHANCE
contains 20, the odds of winning are 1 in 20. The fact that
the condition is looking for a return value of 0 is arbitrary; any value between 0
and
CHANCE-1
would have worked.
The
if-else
Statement
Sometimes we want to do one thing if a condition is true and another thing if
that condition is false. We can add an
else clause
to an
if
statement, making it
an
if-else statement,
to handle this kind of situation. The following is an example
of an
if-else
statement:
if
(height <= MAX)
adjustment = 0;
else
adjustment = MAX - height;
If the condition is true, the first assignment statement is executed;
if the condition is false, the second assignment statement is executed.
Only one or the other will be executed, because a boolean condition
evaluates to either true or false. Note that proper indentation is used
again to communicate that the statements are part of the governing
if
statement.
KEY CONCEPT
An
if-else
statement allows a pro-
gram to do one thing if a condition
is true and another thing if the con-
dition is false.
If Statement
if
(
Expression
)
Statement
else
Statement
An
if
statement tests the boolean Expression and, if true, executes
the first Statement. The optional
else
clause identifies the Statement
that should be executed if the Expression is false.
Examples:
if
(tal < 7)
System.out.println ("Total is less than 7.");
if
(firstCh != 'a')
count++;
else
count = count / 2;
Search WWH ::
Custom Search