The do-while Statement
The do-while statement is like the while statement, except that the associated block always gets
executed at least onc Its syntax is as follows: |
|
do {
statement (s)
} while (booleanExpression);
|
|
Just like the while statement, you can omit the braces if there is only one statement within them.
However, always use braces for the sake of clarity.
|
public class MainClass {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 3);
}
}
This prints the following to the console: |
0
1
2 |
The following do-while demonstrates that at least the code in the do block will be executed once
even though the initial value of j used to test the expression j < 3 evaluates to false. |
public class MainClass {
public static void main(String[] args) {
int j = 4;
do {
System.out.println(j);
j++;
} while (j < 3);
}
}
|
|
This prints the following on the console. |
4 The do while loop in action
do {
// statements
} while (expression);
|
|
public class MainClass {
public static void main(String[] args) {
int limit = 20;
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= limit);
System.out.println("sum = " + sum);
}
}
|
|
sum = 210 http://www.java2s.com/Tutorial/Java/ 0080__Statement-Control/Catalog0080__Statement-Control.htm |
|
|
|
No comments:
Post a Comment