为什么我在这里需要括号? Java:“if(true)int i = 0;”
public class Test{ public void newMethod(){ if(true)int i=0; } }
上面的代码给出了以下错误
Test.java:4: error: '.class' expected if(true)int i=0; ^
但如果我这样写
public class Test{ public void newMethod(){ if(true){ int i=0; } } }
那就没有错误!
我知道这个问题对社区没有帮助,但我真的很好奇为什么我需要在这个声明中有括号。 我已经用java编程了几年,我刚刚遇到这个错误。
顺便说一句,我正在使用JGrasp。
这是我的理解。 引自JAVA SE 7规范的第14章 :
14.2。 块
块是大括号内的语句,本地类声明和局部变量声明语句的序列。
Block: { BlockStatementsopt } ........ BlockStatement: LocalVariableDeclarationStatement ClassDeclaration Statement
所以一个块总是在括号{ ... }
。
14.4。 地方变量声明声明
局部变量声明语句声明一个或多个局部变量名称。
LocalVariableDeclarationStatement: LocalVariableDeclaration ; LocalVariableDeclaration: VariableModifiersopt Type VariableDeclarators ....... VariableDeclarator: VariableDeclaratorId VariableDeclaratorId = VariableInitializer
…….
每个局部变量声明语句都立即被一个块包含。 局部变量声明语句可以与块中的其他类型的语句自由混合。
现在,它是什么意思,“立即包含”?
有些陈述包含其他陈述作为其结构的一部分; 这些其他陈述是陈述的替代。 我们说语句S立即包含语句U,如果没有与S和U不同的语句T使得S包含T而T包含U.同样,一些语句包含表达式(§15)作为其结构的一部分。
我们来看看你的例子:
public class Test{ public void newMethod(){ if(true)int i=0; } }
在这种情况下,我们有以下块:
{ if(true)int i=0; }
在这个块里面我们有一个If Statement
:
if(true)int i=0;
反过来,该语句包含一个局部变量声明:
int i=0;
因此,违反了条件。 回想一下: 每个局部变量声明语句都会立即被一个块包含。 但是,在这种情况下,局部变量声明包含在If语句中,该语句不是块本身,而是由另一个块包含。 因此这段代码无法编译。
唯一的例外是for
循环:
A local variable declaration can also appear in the header of a for statement (§14.14). In this case it is executed in the same manner as if it were part of a local variable declaration statement.
(您可能需要重读几次才能理解。)
黑暗猎鹰是对的,如果if测试之后的单个语句是变量声明,那么没有任何东西可以使用该变量,声明的范围将限制在if结果的主体,这将是无用的,因为任何后续的都不会i
在范围内。
如果if (true)int i = 0;
实际工作(意味着声明对后续行可见),这意味着你是否有一个声明的变量将取决于if测试的结果,这将是不好的。
BTW, if (true) int i = 0;
在Eclipse中导致此语法错误:
Multiple markers at this line - i cannot be resolved to a variable - Syntax error on token "int", delete
虽然它会产生一个警告:虽然它会产生警告:
the value of the local variable i is not used