代码之家  ›  专栏  ›  技术社区  ›  B_Ali_Code

为什么我们不能在没有花括号的while循环之后使用声明语句?[副本]

  •  3
  • B_Ali_Code  · 技术社区  · 7 年前

    如果不使用花括号,为什么我们不能在后面使用声明语句 while

    它配有卷曲支架:

    while(true){
        int u =89;
    }
    

    如果没有大括号,则会发生编译时错误:

    while(true)
        int u =89; // compile time error
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   user207421    7 年前

    句法上的原因是 while 声明是 statement ,其中包括所有可执行语句,特别是块,但不包括声明。

        2
  •  2
  •   Scheff's Cat    4 年前

    我刚刚研究了在oracle上找到的Java语法。通用域名格式: Chapter 18. Syntax . (我希望这是适用于该问题的正确版本。)

    Statement:
    
        Block
        ;
        Identifier : Statement
        StatementExpression ;
        if ParExpression Statement [else Statement] 
        assert Expression [: Expression] ;
        switch ParExpression { SwitchBlockStatementGroups } 
        while ParExpression Statement
        do Statement while ParExpression ;
        for ( ForControl ) Statement
        break [Identifier] ;
        continue [Identifier] ;
        return [Expression] ;
        throw Expression ;
        synchronized ParExpression Block
        try Block (Catches | [Catches] Finally)
        try ResourceSpecification Block [Catches] [Finally]
    

    while 后跟 ParExpression (括号中的表达式)和 Statement .

    while(true){
        int u =89;
    }
    

    这个 之后 虽然 Block 这反过来可能会扩展到 LocalVariableDeclarationStatement

    对于

    while(true)
        int u =89; // compile time error
    

    这个 陈述 属于 虽然 的正文无法扩展到 因为没有

    nd公司 根本不是Java语言的一部分(基于语法)。