Java Reference
In-Depth Information
into the variable
rate
. The statement in Line 8 checks whether the value of the
variable
hours
is greater than
40.0
.If
hours
is greater than
40.0
, then the wages
are calculated by the statement in Line 9, which includes overtime payment; otherwise,
the wages are calculated by the statement in Line 11. The statement in Line 12 outputs
the wages.
Let's now consider more examples of
if
statements and examine some of the common
errors made by beginning programmers.
EXAMPLE 4-13
Consider the following statements:
if
(score >= 90)
//Line 1
grade = 'A';
//Line 2
System.out.println("The grade is " + grade);
//Line 3
Here, you might think that because the statements in Lines 2 and 3 are aligned, both
statements are the action statements of the
if
statement. However, this is not the case.
The
if
statement acts on only one statement, which is
grade = 'A';
. The output
statement executes regardless of whether
(score >= 90)
is
true
or
false
.
Example 4-14 illustrates another common mistake.
EXAMPLE 4-14
Consider the following statements:
if
(score >= 60)
System.out.println("Passing");
System.out.println("Failing");
If the logical expression,
score >= 60
, evaluates to
false
, the output would be
Failing
. That is, this set of statements performs the same action as an
else
statement.
It will execute the second output statement rather than the first. For example, if the value
of
score
is
50
, these statements will output the following line:
Failing
However, if the logical expression,
score >= 60
, evaluates to
true
, the program will
write both statements, giving an unsatisfactory result. For example, if the value of
score
is
70
, these statements will output the following lines:
Passing
Failing
Search WWH ::
Custom Search