【问题标题】:Variable declaration in if clauseif 子句中的变量声明
【发布时间】:2013-04-08 04:39:50
【问题描述】:
if(someCondition)
int a=10;//Compilation Error
else if(SomeOtherCondition){
int b=10;//no compilation Error
}
为什么会发生这种情况。为什么在第一种情况下会出现编译错误。如果我放大括号,则没有编译错误,但对于 if 语句,如果它是一个语句,则大括号是可选的。
【问题讨论】:
标签:
java
if-statement
variable-declaration
【解决方案1】:
您需要在if statement 中定义int a 的范围,它将用花括号{} 定义。
if(someCondition){
int a=10; // works fine
}else if(SomeOtherCondition){
int b=10; //works fine
}
【解决方案2】:
if(someCondition)
int a=10;//Compilation Error - you have to define the scope of int. what scope does it have here? so {} are necessary
else if(SomeOtherCondition){
int b=10;//no compilation Error
}