what does "do" do here? (java)
I saw this bit of code on the interents somewhere. I'm wondering what the do
is for.
public class LoopControl {
public static void main(String[] args) {
int count = 0开发者_如何学运维;
do {
if (count % 2 == 0) {
for (int j = 0; j < count; j++) {
System.out.print(j+1);
if (j < count-1) {
System.out.print(", ");
}
}
System.out.println();
}
count++;
}
while (count <= 5);
}
}
By which I mean what exactly does do
mean? What's its function? Any other information would be useful, too.
It is a do-while loop. So it will do everything in the following block while count is less than or equal to 5. The difference between this and a normal while loop is that the condition is evaluated at the end of the loop not the start. So the loop is guarenteed to execute at least once.
Sun tutorial on while and do-while.
Oh, and in this case it will print:
1, 2
1, 2, 3, 4
Edit: just so you know there will also be a new line at the start, but the formatting doesn't seem to let me show that.
It is similar to a while
loop, with the only difference being that it is executed at least once.
Why? Because the while
condition is only evaluated after the do
block.
Why is it useful? Consider, for example, a game menu. First, you want to show the menu (the do
block), and then, you want to keep showing the menu until someone chooses the exit option, which would be the while
stop condition.
It's a while loop that gets executed at least once.
Edit: The while and do-while Statements
do { ... } while(CONDITION)
ensures that the block inside do will be executed at least once even if the condition is not satisfied, on the other hand a while
statment will never execute if the condition is not met
It goes with the while. do { ... } while() is a loop that has the conditon in the end.
精彩评论