Java Reference
In-Depth Information
LISTING 5.1
continued
System.out.print ("Enter your age: ");
int
age = scan.nextInt();
System.out.println ("You entered: " + age);
if
(age < MINOR)
System.out.println ("Youth is a wonderful thing. Enjoy.");
System.out.println ("Age is a state of mind.");
}
}
OUTPUT
Enter your age:
40
You entered: 40
Age is a state of mind.
Let's look at a few more examples of basic
if
statements. The following
if
statement causes the variable
size
to be set to zero if its current value is greater
than or equal to the value in the constant
MAX
:
if
(size >= MAX)
size = 0;
The condition of the following
if
statement first adds three values together,
then compares the result to the value stored in
numBooks
:
if
(numBooks < stackCount + inventoryCount + duplicateCount)
reorder =
true
;
If
numBooks
is less than the other three values combined, the boolean variable
reorder
is set to
true
. The addition operations are performed before the less
than operator, because the arithmetic operators have a higher precedence than
the relational operators.
Assuming
generator
refers to an object of the
Random
class, the following
if
statement examines the value returned from a call to
nextInt
to determine a
random winner:
if
(generator.nextInt(CHANCE) == 0)
System.out.println ("You are a randomly selected winner!");
Search WWH ::
Custom Search