Lab 8 In-Class: More Loops
Once again you will work in pairs - one member of a pair will be A
and the other B. A is at the keyboard for
the exercises marked B (with the help of
A) and B is at the keyboard for the exercises marked A. Both team
members should test ALL code!
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 (A): 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:
Coin()
- Constructor: creates a new Coin object that has randomly
been flipped
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.
In this case since the class is written in Chapter 5 of the textbook
you can actually see the code (it is on page 178) but that isn't
necessary for using it. However, 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
and Coin.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 179
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.
OR
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")),
then print it (just
CoinFlips.java) out to hand in.
Exercise #2 (B): 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
a 3:
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 then
print it.
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
the program.
- (A) 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.
- (B) 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:
- (B) 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).
- (B) 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!
- (B) 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.
- (B) 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
yards.
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?)
- (B) Print out the name of the quarterback with the maximum number of yards per
completed pass along with the maximum value.
- (A) 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).
- Print the final version of your program.
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
u).
The file Vowels.java contains the skeleton
of the program.
Open it and do the following as indicated in the comments:
- (A) Add declarations for any additional variables you need and initialize
them as appropriate.
- (A) 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).
- (A) 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
Character.isLetter(ch)
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.
- (A) After the loop print out the number of vowels and the total number
of letters, appropriately labeled.
- (B) 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 89-90
for an example).
- (B) [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
phrase).
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!
Print the final version of your program.
Hand in:
- Hardcopy of CoinFlips.java, ForLoops.java
Passes.java, and Vowels.java.
- Zip the files in your directory. As last week use names of both
tema members
in the name of the zip file.
- Submit the zip file to Inquire.