Mini-Lab:
A Whirl of Color
Using Conditional Statements
This set of Mini-Lab Exercises is part of a series in which students
build a small program with several fish moving around in an aquarium.
The set includes the following exercises:
Each section contains an Introduction to a problem
or task, descriptions or examples of one or more
Concepts to apply in solving the problem or
completing the task, and an Exercise.
In the exercises that precede this one, students created three fish, moved
them forward one step, and displayed them graphically. Therefore, students
should be familiar with constructing objects, using variables, and invoking
methods. Some familiarity with logical expressions is also required
for this set of exercises.
About Face!
Introduction
In our current program, fish move to the right and then get stuck at the right
wall. This does not make sense. We can use a Simple
Conditional statement to determine when a fish should turn
around and start swimming the other direction.
Concept: Simple Conditional
When writing a computer program, there are some actions that we
only want to perform some of the time, when a certain condition is
true.
For example, consider a program that simulates a student
getting lunch in a cafeteria. In this case we will simulate a student
who has a sandwich and coffee every day, but almost never eats
dessert. The one exception is when the cafeteria has lemon squares,
this student's favorite.
Example 1: Condition with Single Statement |
Example 2: Condition with Single Statement |
Example 3: Condition with Multiple Statements |
student.takeASandwich();
student.takeCoffee();
if ( caf.hasLemonSquares() )
student.takeALemonSquare();
student.sitDownAndEat();
|
student.takeASandwich();
student.takeCoffee();
if ( caf.hasLemonSquares() )
{
student.takeALemonSquare();
}
student.sitDownAndEat();
|
student.takeASandwich();
student.takeCoffee();
if ( caf.hasLemonSquares() )
{
student.takeALemonSquare();
student.takeALemonSquare();
}
student.sitDownAndEat();
|
Note that an if
statement takes just a single
statement as the one to do when the given condition is true.
If there are several statements to perform as part of the condition,
you must use curly braces ( { } ) to group them into a single
block of statements, as in Example 3 above. You can also use
curly braces around a
single statement, as in Example 2, for consistency or clarity.
Stop and Think
- Which statements in Example 1 will be executed when there are
no lemon squares? In what order will they be
executed? Which statements will be executed, and in what
order, when there are lemon squares?
Exercise
- In your previous testing of the program you may or may not have
noticed that fish swim only to the right and get stuck at the right
wall. To verify the problem, make a copy of the statement that sets
the dimensions of the aquarium.
(Stop and Think:
where is the
statement that sets the dimensions of the aquarium? In what
class, and what method?) "Comment out" the original, and change
the dimensions in the copy to be 100 x 200. Copy the code that moves
and redisplays the fish to let them move a second time. Now run the
program several times and make sure you see the problem.
- Research the AquaFish
specification to find out how to determine whether a fish is at a
wall and how to make it reverse direction.
Modify the
main method to
have each fish check whether to change direction
whenever it moves forward.
(Stop and Think:
You could check whether to reverse direction or not and then
move forward, or you could move forward first and then check
whether to reverse direction. Does the order
matter? Consider three cases: a) for a fish that
was constructed along the left wall, b) for a fish that was
constructed in the middle of the aquarium, and c) for a fish
that was constructed along the right wall. Now ask yourself
again: Does the order matter?)
-
Test your program in the narrower aquarium you created
above. When you are satisfied that your program is
behaving correctly, restore the aquarium to its original
size.
|
One Fish, Two Fish, Red Fish,
Blue Fish
Introduction
Our aquarium is a little boring, since the fish are all the same color. We could
specify the color of each fish as we construct it, giving each fish a different
color.
Or, to make things more interesting, we could decide on the color of each
fish based on a random number.
We can use the
standard Java Random
class to do this.
Exercise: One Red and Two Blue Fish
- Research the AquaFish
class documentation to discover how to specify the color of a fish
as you
create it. Modify the
main method to make your
first fish
Color.RED and your other two fish
Color.BLUE .
(Color.RED and Color.BLUE are
constant Color values defined in the standard
Java Color
class.
Notice that the AquaSimApplication class has an
import java.awt.Color; statement at the top
of the file; this allows you to use the standard Java
Color class even though it isn't one of the
classes you defined.)
- Identify in advance what behavior you expect from your
program when you test it. Do you know which fish will be
which color? Do you know how many fish you should get of each
color? Test your program to make sure that your results
are what you expect.
|
Concept: Two Alternatives
Sometimes there is a situation in which one of two actions is
appropriate, depending on whether a particular condition is true or
not.
When the condition holds you want to do one action; otherwise
you want to do the other.
Consider a variation on the cafeteria lunch example from above.
Rather than simulating a student who only eats dessert when there are
lemon squares on the menu, we might simulate a student who eats
dessert every day, choosing lemon squares when they are available and
cookies when they are not. (Cookies
are always available in this cafeteria.)
The new behavior appears below.
Example: Two Alternatives |
student.takeASandwich();
student.takeCoffee();
if ( caf.hasLemonSquares() )
student.takeALemonSquare();
else
student.takeACookie();
student.sitDownAndEat();
|
Note that the else
line does not include a conditional
expression. It is unnecessary (because it can be deduced
from the if
expression), and, as a result,
it would not be legal Java code.
Concept: Positive Condition
It is generally possible to write a conditional expression as either a
positive or negative expression. Often programmers write down the
more common case first, even if that means writing the conditional
expression in the negative, as in the second example below. Positive
expressions are generally easier to read, however, especially if
the conditional expression is somewhat complicated.
Positive Condition (Preferred) |
Negative Condition |
if ( caf.hasLemonSquares() )
student.takeALemonSquare();
else
student.takeACookie();
student.sitDownAndEat();
|
if ( ! caf.hasLemonSquares() )
student.takeACookie();
else
student.takeALemonSquare();
student.sitDownAndEat();
|
Concepts: Random Numbers,
Saving Returned Values in Variables
One of the standard Java packages,
java.util
,
includes a Random
class that can
be used to create what are known as pseudo-random numbers.
Pseudo-random numbers are as close as computers can get to truly random
numbers; they look and work like random numbers, although they are
generated from computer algorithms and so are not truly random. The
nextInt
method in the Random
class returns a new
random integer, which can be saved in a variable. For
example, in the following code
Random generator = new Random();
int randNum = generator.nextInt(10);
the first statement creates an instance of the Random
class,
a random number generator. The second statement uses this random
number generator to randomly
generate one of the 10 numbers between 0 and 9 (because the parameter to
the nextInt
method is 10
), and save it in the
integer variable called randNum
.
If the parameter to
the nextInt
method were 100
, it would
randomly generate one of the 100 numbers between 0 and 99.
If the parameter to
the nextInt
method were 2
, it would
randomly generate either 0 or 1. This could be
used to simulate a coin toss, for example.
Consider modifying the cafeteria lunch example to simulate a student
who eats dessert everyday, randomly choosing between a cookie or an
apple.
Example: Choosing Randomly |
student.takeASandwich();
student.takeCoffee();
Random generator = new Random();
int randNum = generator.nextInt(2);
if ( randNum == 0 )
student.takeAnApple();
else
student.takeACookie();
student.sitDownAndEat();
|
Exercise: Random Red and Blue Fish
-
Edit your
main method to construct a random number
generator right before you construct your three fish.
Give your new variable a name that conveys its purpose.
(Note: The AquaSimApplication class has an
import java.util.Random; statement at the top
of the file; this allows you to use the standard Java
Random class even though it isn't one of the
classes you defined.)
- After you construct your random number generator and
above the code that constructs your three fish,
create a new integer variable that can store the a random
number. Don't actually generate the random numbers yet,
though.
Give your new variable a name that conveys its purpose.
For example, your variable declaration might
look like the following line.
- Just above the statement that constructs each fish, set
your random number variable to a different random number (0 or 1).
Then use the variable in an if statement to randomly construct
each fish as either
Color.RED or Color.BLUE .
- Identify in advance what behavior you expect from your
program when you test it. Do you know which fish will be
which color? Do you know how many fish you should get of each
color? Test your program to make sure that your results
are what you expect.
- Update the appropriate internal and external documentation
to reflect your changes.
|