【问题标题】: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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      • 2014-04-12
      • 2014-08-26
      • 2016-01-13
      • 2022-09-27
      • 2021-03-04
      相关资源
      最近更新 更多