Java Lesson 6 – Loops (cont’d)
The next loop I want to talk about is the do-while loop. This kind of loop is different from a for loop in that it will loop indefinitely until a condition no longer applies. Think of it as an ‘if’ statement that repeats.
do
{
// code to repeat
} while(condition)
The word ‘do’ marks the beginning of the loop. Inside the code block, you would place the code you’d like to be looped. After the closing curly bracket, you would put the condition inside a while statement. A good way to think about it is that you are saying “do this, this, this, and this as long as (while) the player has not pressed escape.”
The only difference between do-while loops and while loops is that in while loops, you need to meet the condition before you are even allowed to enter the loop, unlike do-whiles where the code in the loop is run once before the condition is checked.
while(condition)
{
// code to be looped
}