Logout

Home Topic 4 Last Next

Looping 1 - The While Loop

(***Be sure to learn the while loop before the for loop.)

Flow of control is accomplished in Java through conditional blocks, method calling, and also looping. Looping is the process of executing a series of lines of code over and over again. Looping is also referred to as iteration; to iterate is to repeat.

There are three main looping strutures, the for loop, the while loop, and the do while loop. The do while loop is not used that much, and the for loop is a little un-intuative, so it makes sense to start with the while loop. Later on, we'll look at an alternative way to loop called recursion (which is basically a method calling another instance of itself).

The While Loop Structure

boolean continueLooping = true;
while(continueLooping){ System.out.println("Loop this!");
System.out.println("Do you want to continue? true/false");
continueLooping = Boolean.parseBoolean(br.readLine());
}

Output would be something like the following, depending on how many times you typed in false:

Loop this!
Are you finished? true/false
false
Loop this!
Are you finished? true/false
false
Loop this!
Are you finished? true/false
true

The first thing to notice is the while line, which is very much like the if line of an if block. Following both if and in this case while is a condition, and if the condition evaluates to true, the block of code is entered. Often the condition is compound and even complex, but in the example above, it's a simple boolean variable, true or false.

(In fact, you could draw a similarity between the way methods, if blocks, and while blocks work. It's not exactly the same, but you can think of ifs and whiles as being methods that take in parameters in the parentheses that immediately follow them. What is in the parentheses in all three cases is information which is to be used inside the block. And this information is are variable, depending on what the variable is, or if it is more complex than a single variable, what the expressions evaluate to.

  • In the case of the method, the parameter in the parentheses will alter the way the method executes.
  • In the case of the if block, the code in the block following the if( ) will only execute if what's in the parentheses evaluates to true,.
  • And in the case of the while, what's in the parentheses will determine whether the while is entered, and, moreover how many times it is entered.)

The other thing to particularly notice, then, is the role of the continue variable throughout the loop (and just before it), in our example. This variable controls the way the while loop works; it is called the Loop Control Variable.

When to Use A While Loop

Sometimes you know exactly how many times you want to loop some lines of code; in that case you should not choose the while loop structure (the for loop structure is better). Rather, a while loop is used when the number of times the loop is to occur is uncertain. In the above examample, we don't know when the user of the program is going to get bored, but sooner or later they will, and sooner or later they will type false, and so have the loop exit.

Another few examples could be: a bank ATM machine when you want to do more than one transaction, a program that gets you to enter names of player signing up for a team, and you don't know how many names there will be, and there are 15 places maximum, or a game that keeps on giving you harder and harder questions until you get three wrong. The while parts of those examples would be something like:

while(anotherTransactionRequested)...

while(anotherPlayerToAdd && placesLeft > 0)...

while(numberIncorrectQs < 3)...

Do note that the condition can be a simple boolean, or any expression, however complex, that evaluates ultimtely to true or false.


One last thing to note is that it is possible for a while loop to not ever be entered. For example, in the full example above, if we had set continue to false, the loop never would have been entered. Or more likely, if we had prompted the user initially with a statement like "Would you like to play along with my silly loop program? true/false", and they typed in false, then the while loop would never be entered; those lines of code would just be skipped.

Note that there actually is a variation of the while loop, the do while loop, in which you always enter the loop at least once. If you want to see how that looks, and why we'd use it, it's on the 4.3.9-X notes page along with a few other branching and looping "extras". For now just remember that the kind of while loop shown here is not necessarily entered at all - though usually it is.

 

Good While Loop Examples

(This code can be copied and pasted directly into an IDE.)

import java.util.Date;
import java.util.LinkedList;
import java.util.Scanner;

public class GoodWhileExamples {
    public static void main(String[] args) {
        //addingToAList();
        //randomUnderCertainValue();
        //certainRemainderOfUNIXTime();
        //loopingTimesIn10Seconds();
    }

    public static void addingToAList(){
        LinkedList<String> students = new LinkedList<String>();
        Scanner snr = new Scanner(System.in);
        boolean continueAddingToList = true;
        while(continueAddingToList){
            System.out.println("What is the name of the next student?");
            String studentName = snr.nextLine();
            System.out.println("Do you want to continue adding students to the list? true/false");
            continueAddingToList = snr.nextBoolean();
            snr.nextLine(); //always when a loop and a nextBoolean or nextInt etc.
        }
    }
    
    public static void randomUnderCertainValue(){
        double num = Math.random(); //returns a random value in the range of 0 to 1
        int counter = 0;
        while(num < 0.9){
            counter++;
            System.out.println("The new value is still under 0.9 for the " + counter + " time");
            num = Math.random();
        }
    }

    public static void certainRemainderOfUNIXTime(){
        Date date = new Date();
        long timeNow = date.getTime(); //gives us "UNIX time" - the number of milliseconds since Jan. 1st, 1970
        System.out.println("timeNow: " + timeNow);
        int counter = 0;
        int divisor = 100;
        while(!(timeNow % divisor == 0)){
            counter++;
            System.out.println("timeNow: " + timeNow);
            System.out.println("We still don't have a UNIX time that is a multiple of " + divisor +
                    "after " + counter + " times.");
            date = new Date();
            timeNow = date.getTime(); //so a new time to check
        }
        System.out.println("So finally we have a time evenly divided by " + divisor + ":" + timeNow + ".");
    }

    public static void loopingTimesIn10Seconds(){
        Date date = new Date();
        long startTime = date.getTime();
        System.out.println("The start time is: " + startTime);
        long tenSecondsFromNow = startTime + 10000;

        int counter = 0;
        boolean underTenSeconds = true;
        while(underTenSeconds){
            counter++;
            System.out.println("Counter: " + counter); //comment this out to see the effect on # times
            Date newDate = new Date();
            System.out.println("The current time: " + newDate.getTime());
            if(newDate.getTime() > tenSecondsFromNow){
                underTenSeconds = false;
            }
        }
        System.out.println("So in ten seconds, the loop executed " + counter + " times.");
    }
}