Loops and the Do-While Loop
You've seen for and while loops before, but this node will review when to use each one and discuss a variety of the while loop.
for & while loops review
If you know how many times a loop will run, you usually should use a for-loop, since you can setup the index variable, condition and increment all in the loop header. For example, the loops below will both print the numbers from 1 to 10, but the for
loop has clearer code:
While Loop
int index = 1;
while(index <= 10){
System.out.println(index);
index = index + 1;
}
For Loop
for(int index = 1; index <= 10; index=index+1){
System.out.println(index);
}
While Loop Needed
In cases that do not depend on a index variable being incremented, you'll need a while loop instead of a for loop. This is often the case when your loop needs to run as long as an external condition is true, such as:
- while a game character is alive
- while a key or button is pressed
- while a user-set variable is an incorrect value.
For example, here's some code for a really simple guessing game. As long as the user does not guess 5
the program will prompt him for another number. Since it will loop until that number is guessed, it needs a while loop:
public static void guessGame()
{
System.out.println("Welcome to the guessing game.");
System.out.println("Guess a Number");
int num = getInput(); //a method which gets user's number input
while(num != 5){
System.out.println("Guess A Number");
num = getInput();
}
System.out.println("5 is Correct!");
}
The above code is pretty simple, so click on the "Menu Example" button below for a similar but larger example. The challenge on the bottom will be to improve some similar code.
In the following code, a help menu will be displayed to the user until they provide a menu selection. Since this will loop until they provide a valid selection, it needs a while loop:
import java.util.*;
class Menu {
public static void javaHelp()
{
int selection = getInput(); //get a number of input
// loop until selection is valid
while(selection < 1 || selection > 3){
System.out.println("Choose an Option to Get Java Help:");
System.out.println(" 1. for");
System.out.println(" 2. while");
System.out.println(" 3. do-while");
selection = getInput();
}
// once selection is in valid range, display menu for that number
if(selection == 1){
System.out.println("for(initialization; condition; iteration){ statment; }");
}
else if(selection == 2){
System.out.println("while(condition){ statement; }");
}
else if(selection == 3){
System.out.println("do{ statement; } while(condition);");
}
}
//This method returns the user's input if it's an integer, and -1 otherwise
private static int getInput(){
Scanner in = new Scanner(System.in);
if( in.hasNextInt() ){
return in.nextInt();
}
else{
return -1;
}
}
public static void main(String args[]){
javaHelp();
}
}
do-while loop
Sometimes, you'll want the code in the loop to run once whether or not the condition is true. For example, in the above guessing game, you will want to display a message and get a number one time, and then repeatedly do that until the user guesses the number.
In such cases you can use a do-while loop. This is identical to the while-loop but it checks the condition after the body of code. This means it will always run once before terminating.
This is the syntax of the do-while loop:
do {
//statements
} while(condition);
The guessing game could be re-written with a do-while loop:
public static void guessGame()
{
System.out.println("Welcome to the guessing game.");
int num;
do {
System.out.println("Guess a Number");
num = getInput();
} while(num != 5);
System.out.println("Correct!");
}
This will do the same thing as the previous code, but it lets you avoid repeating the same print statement and call to getInput()
. By avoiding duplication, the code will be clearer and easier to maintain.
Improved Menu Example
In the original Menu Example code, no instructions were displayed when the Menu was first called. This can be fixed by changing the while loop to a a do-while loop, so the instructions will be displayed before the condition check without having to duplicate code. Edit the code below to use a do-while loop, and remove the duplicate call to getInput()
.
Challenge
Edit the Menu code to use a do-while loop, and only call getInput
from within the loop.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Peter Lacres
Jan 10, 9:11 AMIs the Raw I/O correct? If i test the code without changing it to a do...while loop, i get the same incorrect result for each input as after changing it to a do...while loop. I tested input and first is 0, second is 2, third is 4, other is 3, 5, 1.
Learneroo
Jan 10, 10:28 AM@Peter, The Raw I/O currently just shows some of the input and correct output. Do you want it to show your actual raw output?
Peter Lacres
Jan 10, 11:07 AMAfter each "selection = getInput()" i inserted "System.out.print(selection)" to see the value of selection and it's different from the input in the results. For the other input i was able to
check this by checking the previous submissions page. Here all results are listed. I could be mistaking but i think second input is a 2 instead of a 0.
It would help if Raw I/O would show all the input and output. If the first values are correct and only other input is incorrect it's difficult to find the problem with the code.
thales
Jul 9, 12:33 PMi ad my code link, so you will have the right solution...
my code