Vai*_*ure 4 java variables if-statement
public class Foo{
public static void main(String []args){
int a=10;
if(a==10)
int x=20;
}
}
Run Code Online (Sandbox Code Playgroud)
在编译上面的代码时,编译时会抛出一个错误.
但是,在下面的代码中它很好.为什么?
public class Foo{
public static void main(String []args){
int a=10;
if(a==10){
int x=20;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白.这些究竟发生了什么?据我所知,我们可以在没有花括号的if语句之后编写一个语句(复合语句块).
T.J*_*der 13
为清楚起见,问题在于:
if(a==10)
int x=20;
Run Code Online (Sandbox Code Playgroud)
......错误是error: variable declaration not allowed here.
这是不允许的,因为有一个特定的语句列表是允许的if; 它们在JLS§14.5中有详细说明:
StatementWithoutTrailingSubstatementLabeledStatementIfThenStatementIfThenElseStatementWhileStatementForStatementStatementWithoutTrailingSubstatement (上面的第一件事)包括:
BlockEmptyStatementExpressionStatementAssertStatementSwitchStatementDoStatementBreakStatementContinueStatementReturnStatementSynchronizedStatementThrowStatementTryStatement请注意,LocalVariableDeclarationStatement该列表中不会显示.而LocalVariableDeclarationStatement 被中不允许Block,所以你的第二个例子是罚款.
它为什么不出现在列表中?推测为什么语言设计师会做他们所做的事情总是很危险的.但是到底是什么:让我们说他们允许了.这是什么意思?它的范围仅限于if身体吗?那有点无意义,不是吗?它们除了初始化的副作用(例如int x = foo();)之外没有任何效果,在这种情况下你应该只写下引起副作用的东西(foo();).如果它的范围不仅仅是if它的主体(最终在包含的范围内),那就相当混乱了,不是吗?它似乎不会被宣布,除非if条件是真的......