Java Tutorial: While Loop

Every Tuesday I take some time to put together a java tutorial.  You will notice at the top there is a page indexing them all.  Enjoy!

It has been a couple weeks, but I am back with a new installment of Java Tutorials!

Last time we left off with for loops, and how to use them.  As you noticed, these are very powerful, and they are not even Java specific!  Most programming languages has loops at the core of their abilities.  And usually when you learn the concepts of a loop, the ideas are applied the same (although the syntax might be different.)

But there is more than just the for loop!  There is also the while loop.  It also takes a condition, and repeats the code inside the loop until the condition is met.  Why might we want a different loop?  Can’t we use the for loop for all of our looping needs?  Those are fair questions, and the for loop is quite powerful, but I will give you one reason to want the while loop.

While there are many other reasons, the biggest reason is to keep an entire program running until the user wants to quit.  Sure, you can have a single run through of a program, but most of the time the user might want to go through the process again.  This is especially true about games.  Wouldn’t it be quite annoying to finish a multiplayer match of Call of Duty just to get booted out of the game, and have to restart it?  That would drive most people insane.  So the idea is to keep the program looping back to the multiplayer menu until the user decides to quit.

Lets take a look at a while loop example:

char continue;

boolean quit = false;



    //run the bulk of your program here

    //don't forget to check if the user wants to quit, otherwise there will be an infinite loop!

    System.out.println("Do you want to quit? (y or n);

    continue = scan.nextChar();

    //check to see if the user chose to quit.  If they didn't, keep the loop going.

    if (continue == 'n' || continue =='N')

        quit = true;


Practice Problem

Another use is if you want the user to input as many numbers as they want, and then to find the average of those numbers.  Without predetermining the number of inputs, you can use a while loop to keep going until they enter an escape character or number.

So this practice problem is to take numbers as input from the user, and find the average of those numbers.  If you want, you can also do an outer while loop to allow the user to enter a new set of numbers without restarting the program!  Have fun!


Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: