Java Reference
In-Depth Information
// Set z to the minimum of x and y
if
(x < y) {
z= x;
}
else
{
z= y;
Style Note
13.2, 13.2.1:
indenting if-
statements
}
If the condition
x<y
is
true
, the then-part
{z= x;}
is executed; otherwise,
the else-part
{z= y;}
is executed.
Here is the general form of an if-else statement:
if
(
condition
)
then-part
else
else-part
where the
else-part
is a statement. To give a complete example, we write a pro-
cedure that prints the smaller of its two parameters.
/**
Print the smaller of
b
and
c */
public static void
printSmaller(
int
b,
int
c) {
if
(b < c) {
System.out.println(b);
}
else
{
System.out.println(c);
}
}
2.3.4
Self-review exercises for ifs
In the exercises that ask you to write code, it is best that you actually type them
into your Java IDE and test them to make sure that they work. We recommend
starting a class
Chapter2Exercises
that will contain all the static methods you
write for these self-review exercises.
SR1
. Create a class called
Chapter2Exercises
that does not extend anything.
Write a
public static void
method called
sr1
that has an
int
parameter
x
. Inside
method
sr1
, write a conditional statement that (1) adds
1
to
x
if
x
is negative and
(2) prints the value of
x
. To test this method, try these calls:
Chapter2Exercises.sr1(-3);
Chapter2Exercises.sr1(3);
Chapter2Exercises.sr1(0);
SR2
. What is a
block
?
SR3
. Write a conditional statement that, if
x
is negative, sets
x
to
0
and adds
1
to
y
. The then-part will have to be a block. (If you write this conditional state-
ment in a method, the method should have two parameters.)
Search WWH ::
Custom Search