next up previous
Next: forever And A Day: Up: Loops Previous: Programming while, controlling flow

whileing Away Time: Some Constructions

Great. So now we now what the syntax of a while loop is and roughly what it does. But how do we use it in practice?

The while loop is particularly useful when we don't know how many times we want to execute the code in its block. We can in fact use it if we know exactly how many times we're going to execute the block, and have access to this value before we start executing the loop, but this situation is better handled by a for loop -- another kind of loop that we'll see shortly.

Just for the sake of the story, let's look at how we would use a while loop when we know the number of times that its block of code will be executed, even though we'll show how to do this more nicely using a for statement later.

Let's say that the number of times we want to execute the block is stored in a variable called n, of type int. Then the construction would look like this:


int i = 0;
while (i < n) {
i++;

// block of code to be executed


}

Hang on! We said that we wanted to execute the block only n times, but we've initialized i to be zero -- is this right? Let's see. These are the statements that are executed if we take n to be 3 as an example, and 'unroll' the loop:

  1. i = 0
    1. i < n (0 < 3) evaluates to true
    2. i++ assigns 1 to i
    3. block is executed
    4. jump to top of loop
    1. i < n (1 < 3) evaluates to true
    2. i++ assigns 2 to i
    3. block is executed
    4. jump to top of loop
    1. i < n (2 < 3) evaluates to true
    2. i++ assigns 3 to i
    3. block is executed
    4. jump to top of loop
    1. i < n (3 < 3) evaluates to false: JUMP TO END OF LOOP

Ah yes. It was indeed correct - we ended up executing the block 3 times, just as we had hoped. Note that if we used (i <= n) as the boolean expression in the while statement, then we would have executed the loop 4 times! Be careful of this kind of thing!

At any rate, we know that we don't really want to use a while loop when we have the number of block executions available before we start the loop -- we'll use the for loop for this. How is it that we can get a situation where we don't know the number of times we want to execute the block? (This is the situation where the while loop is most powerful).

Imagine that we're writing our now-famous student registration program. We want someone at a computer to be able to 'register a student', but the problem is that we don't know how many students are going to show up! This is a good example of not knowing how many times we want to execute the loop -- when there is some external situation that will dictate this number.

With a while loop, this is quite easy:


import java.io.*; 
class Test { 

    private static BufferedReader in; 

    public static void main(String[] args) throws IOException { 
            in = new BufferedReader(new InputStreamReader(System.in)); 
            boolean stillProcessing = true;

           while(stillProcessing){

                 // code to register a student goes here

                System.out.println(``Do you want to register another student? (y/n)'');
                String answer = in.readLine();
                stillProcessing = answer.equals(``y'');
           }
        } 
}

In this case, we ask the person at the keyboard whether they want to continue, and if the type y then answer.equals(``y'') evaluates to true, this value is assigned to stillProcessing, and control jumps to the top of the loop where stillProcessing is tested. Since it is true, the block of code executes again.

If the user types anything other than y, the equals statement evaluates to false, control jumps to the top of the loop where stillProcessing is tested, and since it's false, control jumps to the statement following the block of code. In this case this is the end of the method main, but it needn't be in other situations.

A couple of points on style here. Note that the user must type y and nothing else in order to continue processing. That means if the user accidentally hits something else, then the program is going to end. You might want this behaviour, but then again you might want the opposite -- to end the loop only when the user presses n and to continue looping for any other value. To get this behaviour, just replace stillProcessing = answer.equals(``y''); with stillProcessing = ! answer.equals(``n'');. This is interpreted as 'keep processing when answer is not (!) no'.

Another point on style is that since users tend to do all sorts of weird things, we might want to deal with this in other ways. For example, how would you write code so that if the user types anything other than y or n, the program responds by telling them that their input was invalid, and that they should try again? How would you change the program so that the user can type Y or y to continue processing, or n or N to stop processing?

At any rate, you can see that the while loop is particularly useful when we don't know the number of times we're going to process a loop. A very common application of this is when we want to read all the lines in a file, but don't know how long the file is. The construction looks like this:


import java.io.*; 
class Test { 

    private static BufferedReader in; 

    public static void main(String[] args) throws IOException { 
            in = new BufferedReader(new FileReader(``somefile.txt'')); 
            boolean stillProcessing = true;

           String line = in.readLine();
           while(line != null){

                 // code to do stuff with contents of line goes here
                line = in.readLine();
           }
        } 
}

Notice that we're using the fact that the method readLine() returns a null reference when we've reached the end of the file.


next up previous
Next: forever And A Day: Up: Loops Previous: Programming while, controlling flow
Chris Trendall
Copyright ©Chris Trendall, 2001. All rights reserved.

2001-12-09