Java Reference
In-Depth Information
Sample Run: Figure 4-3 shows a sample run of this program.
FIGURE 4-3
Sample run of Example 4-7
The statement in Line 1 displays the input dialog box and prompts the user to enter an
integer. The entered number is stored as a string in
numString
. The statement in Line 2
uses the method
parseInt
of the
class
Integer
, converts the value of
numString
into the number, and stores the number in the variable
number
. The statement in Line 3
copies the value of
number
into
temp
. The statement in Line 4 checks whether
number
is
negative. If
number
is negative, the statement in Line 5 changes
number
to a positive
number. The statement in Line 6 displays the message dialog box and shows the original
number, stored in
temp
, and the absolute value of the number stored in
number
.
EXAMPLE 4-8
Consider the following statement:
if
score >= 90
grade = 'A';
This statement illustrates an incorrect version of an
if
statement. The parentheses around
the logical expression are missing, which is a syntax error.
Putting a semicolon after the parentheses following the logical expression in an
if
statement
(that is, before the statement) is a semantic error. If the semicolon immediately follows the
closing parenthesis, the
if
statement will operate on the empty statement.
EXAMPLE 4-9
Consider the following Java statements:
if
(score >= 90);
//Line 1
grade = 'A';
//Line 2
Search WWH ::
Custom Search