Using For Loops
This set of Mini-Lab Exercises is the third in 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, (usually) abridged versions of one or more Patterns that will be useful in solving the problem or completing the task, and an Exercise.
In the exercises that precede this one, students will have created three fish, moved them forward one space (changing the fish's direction when it is about to hit a wall), and displayed them graphically. Students should be familiar with constructing objects, invoking methods, and using conditional statements and logical expressions.
Students should read over the patterns that appear in this document before the lab.
You are in a situation in which some action should be repeated a known number (N) of times, where N might be a constant number or a value in a variable. The number of repetitions does not depend on any aspect of the repeated action, i.e., you know the value of N before you start the repetition.
Therefore, use a FOR statement that creates a variable to count the number of times the action has been repeated. The counting variable is created and initialized and then, so long as the action has not been repeated too many times (the "test"), the action is done and the count is incremented (the "step"). Express the test as a Positive Condition if possible.
The structure of a FOR loop is:
for (<initialization> ; <condition> ; <step>)
<repeated action>
There are two common idioms for controlling the loop. The first is to count from 0 to N-1, which is the idiom used to ensure a Valid Index in a Linear Indexed Traversal (see the Repetition pattern for detailed information on Linear Indexed Traversal). For example, at the beginning of a card game each player is dealt a hand of cards:
for (int i = 0; i < nbrPlayers; i++)
{ dealHand();
}
The second common idiom for controlling the loop is to count from 1 to N. For example,
for (int i = 1; i <= nbrPlayers; i++)
{ dealHand();
}
You might choose to use the second alternative because it corresponds more closely with counting. On the other hand, the Linear Indexed Traversal pattern is a very common, and important, pattern because it is used to step through one of the most common data structures.
for (int i = 0; i <= nbrPlayers; i++) INCORRECT!
{ dealHand();
}
your action will be repeated nbrPlayers+1 times, not nbrPlayers times. If,
on the other hand, you write
for (int i = 1; i < nbrPlayers; i++) INCORRECT!
{ dealHand();
}
your action will be repeated nbrPlayers-1 times.
To avoid these kinds
of mistakes many people find it easiest to consistently use the
Linear Indexed
Traversal
(i = 0; i < N; i++)
Another alternative is to count down rather than counting up. This alternative and other types of Repetition are described in the complete Repetition Pattern document.
Exercise: Simulate Fish Moving ForwardModify yourmain program to become a simulation of three fish
moving in the aquarium over time.
Initially, set the number of time steps in the simulation to 10.
Choose one of the loop control idioms above and use it correctly.
Don't forget to use pause to slow down the animation enough
for you to see it.
You do not need to print your statistics about how many fish are facing each direction and whether one of your fish has moved left, right, or not at all after each move. Instead, calculate these once after the simulation is complete. |
Keyboard
class provides a number of methods
for getting Prompted Input from the user.
In the Prompted Input pattern, we print a prompt that describes the type of input required from the user and then read in the desired value. A well-written and robust version of this pattern verifies that the input actually provided by the user matches the expectations of the program. For example, if we prompt the user to provide an integer, we should verify that the input is, in fact, a valid integer and not a string, floating point number, or other type.
Exercise: Allow User to Control Simulation StepsResearch the Keyboard specification to discover how to prompt the user for an integer value. Notice that theKeyboard methods are static
methods (like the main function in
FishAnimation.java ). This means that rather than construct
a Keyboard object, you will invoke the method on the
class itself. For example, you could prompt the user for a name
with the following:
The second string passed to the readString method is a
default value. Passing a default value prevents a certain kind of Java
error that we don't want to deal with just now.
Modify your program to ask the user how many times they want the simulation to run, and then use that number to control your loop. Provide a default value (such as 10) when you prompt the user. (Question: Should your prompt appear before or after your message welcoming the user to the aquarium program?) |
Random
class to simulate a coin toss
(or other random selection between two values) by specifying that we want
a random integer in the range 0 to 1.
ExerciseResearch the TempRandom specification to discover how to construct a random number generator and how to use it to randomly generate one of two values (0 or 1). Modify your simulation function to have each fish randomly decide whether to change direction before moving forward. The fish, of course, should also change direction if moving forward means swimming into a wall or out of the aquarium.
Make sure that you have updated the program documentation at the top of the file to reflect your modifications. |