Java Reference
In-Depth Information
Next, we give various examples to show how an
if
statement works. We also show some
common syntax and/or semantic errors that beginning programmers often make.
EXAMPLE 4-6
if
(score >= 90)
grade = 'A';
In this code, if the logical expression,
score >= 90
, evaluates to
true
, the assignment
statement,
grade = 'A';
, executes. If
score >= 90
evaluates to
false
, the assignment
statement,
grade = 'A';
, is skipped. For example, if the value of
score
is
95
, the value
assigned to the variable
grade
is
A
.
4
EXAMPLE 4-7
The following Java program finds the absolute value of an integer.
//Program to determine the absolute value of an integer.
import
javax.swing.JOptionPane;
public class
AbsoluteValue
{
public static void
main(String[] args)
{
int
number;
int
temp;
String numString;
numString =
JOptionPane.showInputDialog("Enter an integer:");
//Line 1
number = Integer.parseInt(numString);
//Line 2
temp = number;
//Line 3
if
(number < 0)
//Line 4
number = -number;
//Line 5
JOptionPane.showMessageDialog(
null
,
"The absolute value of " + temp
+ " is " + number,
"Absolute Value",
JOptionPane.INFORMATION_MESSAGE);
//Line 6
System.exit(0);
}
}
Search WWH ::
Custom Search