问题描述
public class Test{
public void newMethod(){
if(true)int i=0;
}
}
上面的代码给了我如下错误
The above code gives me the following error
Test.java:4: error: '.class' expected
if(true)int i=0;
^
但如果我写这样
public class Test{
public void newMethod(){
if(true){
int i=0;
}
}
}
是没有错误!
我知道这个问题对社区没有帮助,但我真的很好奇为什么我需要在这个语句中括号。我已经在java中编程了几年,我只遇到这个错误只是现在。
I know this question isn't helpful to the community, but I'm really curious why I need to have brackets in this statement. I've been programming in java for a few years and I've only encountered this error just now.
我使用JGrasp的方式。
I'm using JGrasp by the way.
推荐答案
这是我的理解。引用自:
Here is my understanding. Quoting from Chapter 14 of JAVA SE 7 specification:
块是一系列语句,本地类声明和
大括号中的局部变量声明语句。
A block is a sequence of statements, local class declarations, and local variable declaration statements within braces.
Block:
{ BlockStatementsopt }
........
BlockStatement:
LocalVariableDeclarationStatement
ClassDeclaration
Statement
所以一个块总是在大括号 {...}
。
So a block is always in braces { ... }
.
局部变量声明语句声明一个或多个局部
变量名。
A local variable declaration statement declares one or more local variable names.
LocalVariableDeclarationStatement:
LocalVariableDeclaration ;
LocalVariableDeclaration:
VariableModifiersopt Type VariableDeclarators
.......
VariableDeclarator:
VariableDeclaratorId
VariableDeclaratorId = VariableInitializer
.......
每个局部变量声明语句立即包含在一个块中。局部变量声明语句可以与块中的其他类型的语句自由地混合
。
Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.
现在,立即包含是什么意思?
一些语句包含其他语句作为其结构的一部分;
这样的其他语句是语句的子语句。我们说,
语句S立即包含语句U,如果没有语句
T不同于S和U,使得S包含T并且T包含U.在
中以相同的方式,一些语句包含
让我们看看你的例子:
public class Test{
public void newMethod(){
if(true)int i=0;
}
}
在这种情况下,块:
{
if(true)int i=0;
}
If Statement :
Inside this block we have an If Statement
:
if(true)int i=0;
这个语句又包含一个局部变量声明:
This statement, in turn, contains a local variable declaration:
int i=0;
因此,违反了条件。 但是,在这种情况下,局部变量声明包含在一个If语句中,它不是一个块本身,而是由另一个块包含的。
Therefore, the condition is violated. Recall: Every local variable declaration statement is immediately contained by a block. However, in this case the local variable declaration is contained by an If statement, which is not a block itself, but is contained by another block. Hence this code would not compile.
唯一的例外是 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.
(您可能需要重读几遍才能理解。)
(You may need to reread it a few times to understand.)
这篇关于为什么我需要在这里括号? Java:“if(true)int i = 0;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!