Java While Loop
We have made a basic “countdown” program to show how the while loop works in practice:
int countdown = 3;
while (countdown > 0) {
System.out.println(countdown);
countdown--;
}
System.out.println("Happy New Year!!");
Let’s imagine we play a game of Yatzy to show how the while loop and an if else statement work in practice:
Put “Yatzy!” in print. Should the dice yield a six:
int dice = 1;
while (dice <= 6) {
if (dice < 6) {
System.out.println("No Yatzy.");
} else {
System.out.println("Yatzy!");
}
dice = dice + 1;
}
The loop outputs “No Yatzy” if it receives values between 1 and 5. It prints “Yatzy!” each time the value of 6 is exceeded.
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.