问题
Can you please explain why there is no output or blank output for the following java code containing do while loop?
public class Main
{
public static void main(String[] args) {
int i = 10;
do while ( i < 10 )
System.out.print("The value of i is " + i);
while ( i > 10 ) ;
}
}
回答1:
it doesn't run this:
do while ( i < 10 )
because of this:
i = 10;
回答2:
First, a do while loop works as follows:
do {
// code...
} while(condition);
And this loop executes the code in the brackets as long as the condition is evaluated to true.
Second, in your code the condition is false, because i is not less than 10.
A fix would probably look something like this:
int i = 0;
do {
i++;
System.out.print("The value of i is " + i + "\n");
} while ( i < 10 );
All depending by the wanted logic.
回答3:
That is the incorrect syntax for a do-while loop. Try the following code.
int i = 10
do {
System.out.println("The value of i is " + i);
} while (i > 10);
You only need the while statement at he end and curly braces after the do statement like this
do {
} while (expression);
Even with the correct syntax nothing will print because i is 10 and the do-while loop only runs when i is more than 10.
回答4:
Your code, with appropriate braces, looks like this
int i = 10;
do
{
while ( i < 10 )
{
System.out.print("The value of i is " + i);
}
}
while ( i > 10 );
i
is exactly 10, which is not greater than or less than 10, so neither condition is satisfied.
You also never update the value of i
so even if one of the conditions were satisfied, your program would enter an infinite loop.
来源:https://stackoverflow.com/questions/63451780/why-there-is-no-output-or-blank-output-for-this-java-code-containing-do-while