Loops and the Do-While Loop
Premium Content - Free Preview
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.
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