You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Java中do-while循环的while后无分号却未触发语法错误?

Why No Syntax Error When Missing a Semicolon After the Inner 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:

  1. The outer structure is a do-while loop. Instead of a single line of code or a braced block after do, it’s directly followed by a full while loop (this becomes the body of the outer do-while).
  2. That inner while loop has its own body: the System.out.print(...) statement. Since it’s a single line, it doesn’t need braces either.
  3. 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 after while(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 (since i starts 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 i ever became greater than 10 (which it never will here), the outer do-while would run the inner loop again. But since i stays 0, the outer while(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:34:34