Java while and do while Loop
Use a while loop when you do not know how many times you need to repeat, and you only know the condition.
while loop
The condition is checked before each round. If it is false at the start, the body never runs.
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("i = " + i);
i++; // do not forget to change the variable
}
}
}
Output
i = 1
i = 2
i = 3
i = 4
i = 5
do while loop
The body runs first and then the condition is checked. So it runs at least one time.
public class Do {
public static void main(String[] args) {
int i = 10;
do {
System.out.println("Runs once, i = " + i);
i++;
} while (i < 5);
int j = 10;
while (j < 5) {
System.out.println("never printed");
}
System.out.println("done");
}
}
Output
Runs once, i = 10
done
Example: digits of a number
public class Digits {
public static void main(String[] args) {
int number = 9475;
int sum = 0;
while (number > 0) {
sum += number % 10; // last digit
number /= 10; // remove last digit
}
System.out.println("Sum of digits: " + sum);
}
}
Output
Sum of digits: 25
Example: ask again until the input is right
import java.util.Scanner;
public class Valid {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = -1;
while (age < 0 || age > 120) {
System.out.print("Enter your age: ");
if (sc.hasNextInt()) {
age = sc.nextInt();
} else {
sc.next(); // throw away the bad input
}
}
System.out.println();
System.out.println("Age saved: " + age);
}
}
Output
Enter your age: Enter your age: Enter your age:
Age saved: 20
for or while?
| Loop | Use when |
|---|---|
| for | You know the number of rounds, or you count |
| while | You repeat until a condition changes |
| do while | The body must run at least once (menus, input) |
Infinite loop
while (true) {
// runs for ever, use break to stop
}
Note:
The most common bug is to forget to change the loop variable, so the condition never becomes false and the program hangs. Next: Java break and continue.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |