2013-01-07 24 views
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语句表示编译错误错误上如果条件的java

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。这两种说法如何不同,请给我解释一下。如果问题很简单,不好意思。

+0

在第二个例子中,你可以加入一些代码使用'B',而这是很难设计一个可以使用'a'的例子。 –

+1

[为什么控制结构的条件需要在一个块中声明](http:// stackoverflow。com/questions/13647323/why-do-declarations-following-conditions-of-a-b) – jlordo

回答

8

它是在java语言规范中指定的。所述IfThenStatement被指定为

if (Expression) Statement

int a = 0;不是语句,但一个LocalVariableDeclarationStatement(这是不一个Statement亚型)。但BlockStatementLocalVariableDeclarationStatement是块的合法内容。

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

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

参考

13

要确定int a的范围,您需要大括号。这就是为什么你会得到编译器错误

if(true) int a = 0; 

,而这个工程:

if(true){ 
    int b =0; 
} 

JLS §14.9 if语句,

IfThenStatement: 
    if (Expression) Statement 

虽然if(true) int a = 0;int a = 0LocalVariableDeclarationStatement

0

定义变量se parately。并在If中分配你想要的值。如果你这样做,它只会是if块内的一个变量。但既然你有一条线,如果阻止它真的没有意义。

+2

我试过它可以正常工作。我想知道为什么我的上面的代码不起作用。 – wh0