Java Reference
In-Depth Information
EXAMPLE 4-10
Consider the following statements:
if
(hours > 40.0)
//Line 1
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0);
//Line 2
else
//Line 3
wages = hours * rate;
//Line 4
If the value of the variable
hours
is greater than
40.0
, then the
wages
include overtime
payment. Suppose that
hours
is
50
. The logical expression in the
if
statement in Line 1
evaluates to
true
, so the statement in Line 2 executes. On the other hand, if
hours
is
30
,
or any number less than or equal to
40
, the logical expression in the
if
statement in Line
1 evaluates to
false
. In this case, the program skips the statement in Line 2 and executes
the statement in Line 4—that is, the statement following the reserved word
else
executes.
In a two-way selection statement, putting a semicolon after the right parenthesis and
before
statement1
creates a syntax error. If the
if
statement ends with a semicolon,
statement1
is no longer part of the
if
statement, and the
else
part of the
if
...
else
statement stands by itself. There is no stand-alone
else
statement in Java; that is, the
else
statement cannot be separated from the
if
statement. This also creates a syntax
error.
EXAMPLE 4-11
The following statements show an example of a syntax error:
if
(hours > 40.0);
//Line 1
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0);
//Line 2
else
//Line 3
wages = hours * rate;
//Line 4
Because a semicolon follows the closing parenthesis of the
if
statement (Line 1), the
else
statement stands alone. The semicolon at the end of the
if
statement (see Line 1)
ends the
if
statement, so the statement in Line 2 separates the
else
clause from the
if
statement. That is,
else
is by itself. Because there is no separate
else
statement in Java,
this code generates a syntax error.
Search WWH ::
Custom Search