Lab 9 In-Class: While Loops
As usual, create a subdirectory for this lab, open up the Web version of
this handout in Mozilla Firefox, and open Eclipse.
Exercise #1: Infinite Loops and Loop Counters
Breaking out of infinite loops: One of the first things you need
to learn about loops is how to break out of infinite loops! Different
systems have different keys for doing this. In Linux,
CTRL-C stops a program that is running. In Eclipse, there is a
red square on the console window that you click to stop the program.
The program in LoveCS.java should print
"I love Computer Science!!" as many times as the user wishes.
Copy it to your directory and
compile and run it to see how it works.
Clearly the program has a problem and it is a typical one when
writing loops - there is no update of the loop control
variable. Modify the program as follows:
- Fix the loop so it will execute exactly the number of times
specified by the limit. Do not change any of the current
code - just add the update of the loop control variable in the correct
place.
- Modify the code so that each line in the output is numbered.
So if the user enters 3, your program should
print this:
Counter before the loop begins: 1
Loop ...
1 I love Computer Science!!
2 I love Computer Science!!
3 I love Computer Science!!
Counter after the loop ends: 4
- One problem students often have with loops (and with if statements)
is adding semicolons where they don't belong. Add one at the end of
the condition in the while statement above - so your while now looks like:
while (count <= limit);
{
...
}
Run the program and see what happens. Why did the program do
what it did?
- After correcting the problem introduced above,
add a second loop after the one that is
there that does exactly the same thing (including the print statement
after the loop) but initialize the loop control
variable count to 0 instead of 1 and make the other adjustments
necessary. HINTS: First, copy the code for the first loop (including
the initialization and print statements both before and after) and
paste it in after that loop. Then to make changes
think about the order in which the statements inside the loop
are executed - do not change the statement that prints the message.
Run the program and make sure it prints the numbered message
the given number of times twice (a blank line should be printed in between!).
- Now add a third loop after the others that again prints the
"I love Computer Science" message the given number of times but
this time count down. So if the user wants to print the message
three times the program would print (after the other printing from
the other two loops) the following. Again, do not change the code
in the print statement; instead change the variable that counts so
it counts down.
Loop control variable before the loop begins: ______
Loop ...
3 I love Computer Science!!
2 I love Computer Science!!
1 I love Computer Science!!
Loop control variable after the loop ends: _____
- Finally, add a fourth loop that counts by 2 from 2 up to the
limit. As before leave the print statement in the loop alone; make
the count variable do all the work. If the user enters 8 for the
limit, your program should print the following:
Counter before the loop begins: _______
Loop ...
2 I love Computer Science!!
4 I love Computer Science!!
6 I love Computer Science!!
8 I love Computer Science!!
Counter after the loop ends: ______
- Print this program to turn in (be sure your name is typed in
the program before you print!).
Exercise #2: Summing in a Loop
As we have seen in class one task a loop often performs is adding up
some values. In this exercise you will complete a program that
adds up the points scored in a specified number of games (the number
is input to the program) and finds the average number of points
scored per game. The basic program will contain a count-controlled
loop that reads in scores and adds them up.
- The file GameStats.java contains
a skeleton of the program. Download the file, open it and observe
that it already has declared the variables you need to make
the loop do its job:
- A variable to hold the total number of games (numGames)
- A variable to count the games, one at a time (gameCount)
- A variable to hold each score read in (score)
- A variable to hold the sum of the scores (totalPoints)
Complete the program using the comments as a guide. Run the
program several times with different numbers of games to make
sure it works.
- Using a loop to verify input Often a loop is used in an
interactive program to force the user to enter valid input - when the
user enters an invalid input value the loop keeps asking for and
reading in a new value until something correct is entered. The general
structure of the loop is as follow:
...
Prompt for and read in the input
while ( ... the input is not valid ...)
{
Let the user know the input is not valid
Ask them to try again
Read in the new value
}
... continue the program - now the input is guaranteed to be valid
Suppose a valid score in this game (whatever it is!)
is in the range 0 - 250. Add a validation loop
inside the current loop (a loop inside a loop is called a nested loop)
to guarantee that the user enters a valid score. The structure
of your program will be as follows (you must translate it into correct
Java!):
while ( ....... ) // this is your current while statement
{
...
System.out.print ("Enter the points scored in game " + gameCount):
score = scan.nextInt();
// Validate the score
while ( ... score is not valid ... )
{
Tell the user the score is not correct
Ask the user to enter a score in the correct range
Read in the new score
}
// Process the score - from here on out the code is what
// you already have
Test your program thoroughly. Make sure it catches all types of
incorrect input.
- Finally change the loop control condition (the main loop, not
the validation loop) so that the loop stops either when a perfect
score is obtained (a score of 250) or the specified number of games
has been reached. After the loop add a statement that
prints a congratulations message if the loop ended because of a perfect
score. Test your program thoroughly.
- Print your completed program to turn in.
Exercise #3: A Guessing Game
File Guess.java contains a skeleton for a
program to play a guessing game with the user. The program should randomly
generate an integer between 1 and 10, then ask the user to try to
guess the number. As long as the
user guesses incorrectly, the program should ask him or her
to try again; when the guess is correct,
the program should print a
congratulatory message.
- Using the comments as a guide, complete the program so that it plays
the game as described above.
- Modify the program so that if the guess is wrong, the program
says whether it
is too high or too low. You will need an if statement (inside
your loop) to do this.
- Now add code to count how many guesses it takes the user to get
the number, and print this number at the end with the congratulatory message.
- Finally, count how many of the guesses are too high, and how many are too low;
print these values, along with the total number of guesses, when the user
finally gets it.
- Print this program to turn in.
Exercise #4: Flipping a Coin
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 on pages 221 - 222 of the textbook. The class is in the file
Coin.java. Do the following
to complete the program.
- Save CoinFlips.java and Coin.java to your directory.
- Open your book to pages 220 - 222 to study the Coin class and
a simple program that uses it (that example does not use a loop).
- Open CoinFlips.java in Eclipse and add code as directed by
the comments.
- 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.
- Print out CoinFlips.java to hand in.
What to Hand In
- Hardcopy of LoveCS.java,
GameStats.java, Guess.java, CoinFlips.java.
- Tar up your lab9 directory and e-mail it to your instructor with
cpsc120 lab9 in the subject line.