4
public class SomeClass{

    public static void main (String[] args){
        if(true) int a = 0;// this is being considered as an error 
        if(true){
            int b =0;
        }//this works pretty fine
    }
}//end class

在上面的类中,首先 if 语句显示编译错误

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Syntax error on token "int", delete this token
    a cannot be resolved to a variable

但是第二个 if 语句工作正常。我只是无法自己弄清楚。我知道在单个语句中声明变量是没有用的if。这两种说法有何不同,有人可以解释一下。对不起,如果问题真的很简单。

4

4 回答 4

13

要定义int a你需要花括号的范围。这就是为什么你得到编译器错误

if(true) int a = 0;

虽然这有效:

if(true){
    int b =0;
}

有关if 语句,请参阅JLS §14.9 ,

IfThenStatement:
    if ( Expression ) Statement

在 中时if(true) int a = 0;int a = 0LocalVariableDeclarationStatement

于 2013-01-07T10:25:21.043 回答
8

它在 java 语言规范中指定。被IfThenStatement指定为

if ( Expression ) Statement

int a = 0;不是语句,而是一个LocalVariableDeclarationStatement不是的子类型Statement)。但是 aBlock是 aStatement并且 aLocalVariableDeclarationStatement是块的合法内容。

 if (true) int a = 0;
           ^--------^    LocalVariableDeclarationStatement, not allowed here!

 if (true) {int a = 0;}
           ^----------^  Statement (Block), allowed.

参考

于 2013-01-07T10:36:58.927 回答
5

从 java 语言规范 §14.2 中,您可以看到LocalVariableDeclaration不是Statement,因此只能出现在BlockStatement中:

BlockStatement:
    LocalVariableDeclarationStatement
    ClassDeclaration
    Statement

参考:http ://docs.oracle.com/javase/specs/jls/se7/jls7.pdf

于 2013-01-07T10:34:13.473 回答
0

单独定义一个变量。并在 If 中分配您想要的值。如果你这样做,它只会是 if 块内的一个变量。但是既然你有一行 if block 它真的没有意义。

于 2013-01-07T10:26:15.040 回答