Espresso: A Concentrated Introduction to Java


Laboratory: Loops

Summary: In today's laboratory, you will ground your understanding of loops in a few short examples.

Contents

Exercises

Exercise 0: Preparation

a. Start Eclipse, and create the package username.loops within the Code project.

Exercise 1: Counting

a. Write a main class, SimpleCounter, that prints the numbers from 1 to 10 using a for loop.

b. Write a main class, EvenCounter, that prints the even numbers from 0 to 20 using a for loop.

c. Write a main class, DownCounter, that prints the numbers from 10 to 1 using a for loop.

Exercise 2: Counting, Revisited

a. Write a main class, Counter, that prompts the user for three integers -- a starting value, an ending value, and an increment -- and then prints all integers starting with the starting value and ending just before or at the ending value. For example,

This program counts for you.
Please enter the starting value: 5
Please enter the ending value: 10
Please enter the increment: 1
5 6 7 8 9 10

Similarly,

This program counts for you.
Please enter the starting value: 5
Please enter the ending value: 12
Please enter the increment: 3
5 8 11

You may assume that the user will enter a positive value for the increment.

I would recommend that you use your username.util.IO to read integers. (To do so, you will have to import it since it belongs to a different package.)

Exercise 3: Repetitive Prompting

One typical simple use of loops is to validate input from the user. For example, we might want to repeatedly ask for a password until the password is guessed, or we might want to ask for a color until the user enters a color (instead of something that we could not consider a color, like "Textbook").

a. Write a main class that repeatedly asks the user for a day of the week until the user enters something acceptable. You may choose the meaning of the word acceptable, but you should minimally accept Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. You might also accept abbreviations, such as mon or M.

b. Put the code for prompting into a method called readDay in a utility class called Prompter. (Recall that a utility class does not need a main method: we will always call the methods of the utility class from other classes.) The readDay method will probably need at least two parameters: a BufferedReader to read input and a PrintWriter to print prompts. The readDay method should return a string, preferably one of the seven full names of week days.

c. Rewrite your class from step a to use readDay. For example,

String day = Prompter.readDay(eyes,pen);
pen.println("It appears that you have entered the day " + day);

Exercise 4: Reading until End-Of-File

Another common usage for loops is reading and processing every record in a file, without needing to know in advance how many there will be.

a. Write a short program that you can use to determine experimentally what a call to eyes.readLine() returns if you attempt to read more records from a file than actually exist. (For example, you could create a file with two lines, and then call eyes.readLine() to read from the file three times. To learn something from this, you will also want to print out the string returned by the third call.)

b. In Java, any reference variable that has not yet been assigned a value will evaluate to the special value null. For example, after the following lines of code, the string str evaluates to null. (What this really implies is that the reference variable does not currently point to any object.)

  public static void main(String[] args) {
     String str;

     ...
  }

As you should have seen in the previous exercise, eyes.readLine() also returns null if you try to read past the end of a file, and we can use this to write loops that read every record in a file (i.e., that continue reading records until eyes.readLine() returns null).

Modify your program from the previous exercise such that it repeatedly reads a line from a file and prints it to the console. Your program should stop reading after eyes.readLine() returns null. (Java will certainly allow you to write a test such as this: "if (eyes.readLine() == null)", but it may not be what you want to do. The trouble is that this construct does not store the returned strings, so you will not be able to print them. Instead, you will want to store the strings, and then check what value was returned.)

Exercise 5: Nested Loops

In Java, as in other languages, we can put loops inside other loops. We say that the inner loop is "nested" within the outer loop.

Write a main class called NestedCounting that produces output similar to the following.

10 11 12 13 14 15
20 21 22 23 24 25
30 31 32 33 34 35

Note that loops can be nested as deeply as we wish (i.e., we can have loops within loops within loops...). We can also write conditional statements inside loops and loops inside conditional statements to produce the "flow of execution" needed by the logic of a program.

Extra Work

If you finish the lab early, you may want to try the following.

Iterative sqrt Method

Make a new version of your MyMath.sqrt method. The code for this version should be based on iteration (i.e., a loop), rather than recursion. Of course, if your previous version was iterative, you should now write a recursive version.


Written and revised by Samuel A. Rebelsky, 2005-2006.
Revised further by Marge M. Coahran, 2006-2007.
Samuel A. Rebelsky
rebelsky@grinnell.edu
--->