Lab 8 In-Class: More Loops
As usual, create a lab8 subdirectory for today's lab, open up Firefox
and the Web version of this handout, and open Emacs.
Exercise #1: Flipping a Coin using a do ... while loop
The file CoinFlips.java has the outline
of a program that will flip two coins until at least one of them
comes up heads 10 times. The coins will be objects defined in the
Coin class in the textbook. You have been using objects defined
in classes in the Java Standard Library (String objects, Random
objects, Color objects, Graphics objects). The same idea applies
to using objects defined in a class written by anyone. As you recall in order
to use an object you needed to know how to instantiate the object
(so you needed to know the signature of the constructor to see
what you needed for parameters when you instantiate)
and you needed to know the methods that you could use (and in order
to use these you needed to know the signatures). For the Coin class
the methods and their signatures are as follows:
- Constructor: creates a new Coin object that has randomly
public void flip()
- Flips the coin by randomly choosing a face value.
public boolean isHeads()
- Returns true if the current face of the coin is heads;
returns false otherwise.
To use the class
you need to have the code in the directory with your program.
The class is defined in the file
Coin.java. Now do the following
to complete the program.
- Save CoinFlips.java
to your directory.
- Open CoinFlips.java in Emacs and add code as directed by
the comments. You may want to study the program on page 185
to see an example of instantiating a Coin object and using the
flip and isHeads methods.
- Compile and run the program. Test it thoroughly. Be sure your
final messages after the loop have all the required information.
You may format the output as you wish but an example would be:
Coin 1 beat Coin 2 getting to 10 heads. It took 23 flips.
Coin 2 had 7 heads.
Coin 1 and Coin 2 tied - they reached 10 heads in 19 flips.
- Be sure the program is properly indented (select the region you want
to indent with CTRL-x CTRL-p or with the
mouse or keys, then press Alt-Ctrl-\ ("indent region")).
Exercise #2: Basic For Loops
In this exercise you will write two very basic for loops. The file
ForLoops.java contains a skeleton of the
program. So, do the following:
- Add a for loop that prints the following Halloween message
as many times as the
user wishes (there is already a prompt and read statement to read in
the number of times). Your output should be as follows if the user enters
Boo! - 1
Boo! - 2
Boo! - 3
- Compile and run your program to be sure it is correct so far.
Be sure that the body of your loop and your print statement are as
simple as possible.
- Now add a for loop that prints multiples of 3 from 300 down to 3.
The body of the loop should be one print statement; all the work should
be in the header of the for statement.
- Test your program and be sure it is indented properly.
Exercise #3: Finding Maximum and Minimum of a Sequence of Numbers
A common task that must be done in a loop is to find the maximum and
minimum of a sequence of numbers. In this exercise you will
write a basic count controlled for loop that reads in the number
of completed passes and the total yards passed, then
computes the average number of yards per completed pass for each of
several quarterbacks. After getting the basic loop you will add code
to find the quarterback with the maximum number of yards per
completed pass and the one with the minimum. The program should
read in the number of quarterbacks then for each quarterback
read in the number of passes completed,
and the total number of yards completed.
The file Passes.java contains a skeleton of
- Complete the program by adding the for loop. Note that for
each quarterback you read in three pieces of information (name,
number of completed passes, total number of yards), then you
calculate the number of yards per completed pass and print that
along with the quarterback name. Be sure
to thoroughly test the program.
- Now you will add code to find the maximum number of yards
per completed pass.
In general to find the maximum of a sequence of values processed in a loop
you need to do two things:
- You need a variable that will keep track of the maximum of the values processed so far.
This variable must be initialized before the loop. There are two standard techniques
for initialization: one is to initialize the variable to some value smaller
than any possible value being processed; another is to initialize the variable to
the first value processed. In either case, after the first value is processed
the maximum variable should contain the first value. For this program
declare a variable
maxYards to hold the maximum yards per completed pass. Initialize it
to -1000 (a value less than any legitimate value).
- The maximum variable must be updated each time through the loop. This is done
by comparing the maximum to the current value being processed. If the current value
is larger, then the current value is the new maximum.
So, in the quarterback program, add an if statement inside the loop to compare the current
number of yards per completed pass
to maxYards. If the current number of yards is larger set maxYards to that number.
NOTE: If the current number of yards per completed pass
is NOT larger, DO NOTHING!
- Print out the maximum after the loop. Test your program to make sure it is
correct. Be sure to test it on at least three scenarios: the first quarterback
has the maximum, the last quarterback has the maximum, and the maximum occurs
somewhere in the middle of the list.
- Often we want to keep track of more than just the maximum - we want to
keep information about who has the maximum or where that maximum occurs.
In this case
we should keep track of the name of the quarterback who
has the maximum. To do this
we need to save the current value of the name variable when we update
the maxYards variable. This of course requires a new variable to
store the name of the quarterback with the maximum so far.
Declare nameOfMax (type String)
to keep track of the name of the quarterback who currently has the maximum
Modify your if statement so that in addition to updating maxYards
you also save the value of name in the nameOfMax variable. (WARNING:
you are now doing TWO things when the if condition is TRUE - so,
what do you need to add in your code?)
- Print out the name of the quarterback with the maximum number of yards per
completed pass along with the maximum value.
- Finally, add code to find the minimum yards and the name of the quarterback
with the minimum. The idea is the same as for the maximum. NOTE: Use a separate if when
updating the minimum yards variable (that is, don't add an else clause
to the if that is already there).
Exercise #4: String Processing and Nested Loops
Programs often need to go through strings, character by character,
to find out something about the string. Word processors, compilers,
and command line interpreters (such as the Linux shell) are examples
of programs that work extensively with strings.
In this exercise you will write a program that reads in a
phrase or sentence and determines
the percentage of letters in the phrase that are vowels. The program must
count all the letters in the phrase and count the vowels (a, e, i, o, and
The file Vowels.java contains the skeleton
of the program.
Open it and do the following as indicated in the comments:
- Add declarations for any additional variables you need and initialize
them as appropriate.
- Change the phrase read in to all lower case for easier processing
(so you don't have to test for both upper and lower case vowels).
- Write a for loop to go through the phrase character by character. In
the body of the for loop you need to determine if the current character
is a letter. If it is you need to count it and then see if it is a vowel.
There are several ways to determine if a character is a letter including
different ways of comparing characters.
However, another way is to use the isLetter method from the
Character class. The signature of the method is as follows:
public static boolean isLetter(char c)
Recall that a static method is called using the
class name. Hence, a call would have the form
where ch is a variable of type
char. Since a boolean is returned the above call should be placed in
an appropriate place for a boolean such as an if.
- After the loop print out the number of vowels and the total number
of letters, appropriately labeled.
- Also compute and print the percentage of letters that are vowels.
Use a percent formatter object from the NumberFormat class to print the
percent. To do this you need to do the following (see pages 90-92
for an example).
- [READ ALL BEFORE DOING ANYTHING!!]
It would be nice to have the program let the user keep entering phrases
rather than having to restart the program every time. To do this we need
another loop surrounding the current code. That is, the current loop will be
nested inside the new loop. Add an outer while loop that will continue
to execute as long as the user does NOT enter Q or q for the phrase. Note that
this makes the outer loop a sentinel controlled loop -- the program is
processing phrases and a special value Q will stop it. The outline of the
program is as follows:
read in the first phrase
while the phrase is neither "Q" nor "q"
initialize the counters etc. to set up the for loop
for loop to count letters and vowels in the phrase
print the number of vowels & letters and percentage of vowels
read in the next phrase or "Q" to quit
Note that all you need to do is add the sentinel controlled while loop
around the code you already have. Be sure the code to initialize the
counters is inside the while loop (you start the counters over for each
Be sure to go through the program and properly indent after adding
code (with nested loops the inner loop should be indented). Emacs will
do the work for you!
To submit your code: Tar the files in your lab8 directory
(be sure to name the file with your names, not lab8.tgz)
and cp the tgz file to the directory: