条件java的错误

wh0*_*wh0 4 java

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
Run Code Online (Sandbox Code Playgroud)

在上面的类中,第一个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
Run Code Online (Sandbox Code Playgroud)

然而,第二个if语句工作正常.我自己也搞不清楚.我知道在单个语句中声明变量是没有用的if.这两个陈述如何不同可以请一些人解释一下.如果问题非常简单,请原谅.

Nan*_*ale 13

要定义int a你需要花括号的范围.这就是你得到编译器错误的原因

if(true) int a = 0;
Run Code Online (Sandbox Code Playgroud)

虽然这有效:

if(true){
    int b =0;
}
Run Code Online (Sandbox Code Playgroud)

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

IfThenStatement:
    if ( Expression ) Statement
Run Code Online (Sandbox Code Playgroud)

if(true) int a = 0;,int a = 0是,是LocalVariableDeclarationStatement


And*_*s_D 8

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

if ( Expression ) Statement

int a = 0;不是声明,而是a LocalVariableDeclarationStatement(不是子类型Statement).但是a Block是a Statement和a LocalVariableDeclarationStatement是块的合法内容.

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

 if (true) {int a = 0;}
           ^----------^  Statement (Block), allowed.
Run Code Online (Sandbox Code Playgroud)

参考


Chr*_*ris 5

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

BlockStatement:
    LocalVariableDeclarationStatement
    ClassDeclaration
    Statement
Run Code Online (Sandbox Code Playgroud)

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