为何Java中do-while循环的while后无分号却未触发语法错误?
while? Let’s break this down step by step—your code isn’t actually missing a required semicolon; it’s just using Java’s loop syntax in a way that’s easy to misread at first glance.
First, let’s clean up the code to make the structure clearer (replacing the escaped </> with actual operators):
import java.util.*; import java.lang.*; import java.io.*; class Ideone { public static void main (String[] args) throws java.lang.Exception { int i = 0; do while (i < 10) System.out.print("The value of i is " + i); while (i > 10); } }
The Key Syntax Rule Here
In Java, any loop (while, do-while, for) can have a single statement as its body—you don’t have to wrap the body in curly braces {}. That single statement can even be another loop.
In your code:
- The outer structure is a
do-whileloop. Instead of a single line of code or a braced block afterdo, it’s directly followed by a fullwhileloop (this becomes the body of the outerdo-while). - That inner
whileloop has its own body: theSystem.out.print(...)statement. Since it’s a single line, it doesn’t need braces either. - The semicolon you thought was missing? It’s not required here—because the inner
while’s body is the print statement, not an empty loop. If you did add a semicolon afterwhile(i <10), that would mean the inner loop has an empty body, and the print statement would run once after the loop (but that’s a different scenario).
What This Code Actually Does
- First, the inner
while(i <10)runs indefinitely (sinceistarts at 0 and never gets incremented—oops, that’s a bug, but not a syntax error). It will keep printing "The value of i is 0" forever. - If somehow
iever became greater than 10 (which it never will here), the outerdo-whilewould run the inner loop again. But sinceistays 0, the outerwhile(i>10)condition is always false, so the outer loop only executes once (well, the inner loop runs forever, so we never get to the outer condition check anyway).
Making the Structure Explicit
Adding curly braces makes the nested structure obvious, which avoids confusion:
do { while (i < 10) { System.out.print("The value of i is " + i); } } while (i > 10);
This is exactly equivalent to your original code—no syntax issues because every loop has a valid body, and all required semicolons are present (the one at the end of the outer do-while).
内容的提问来源于stack exchange,提问作者Manas Tripathi

