如何在if之外的if语句中使用声明的变量?

时间:2012-11-08 08:32:07

标签: java

如何使用我在if块之外的if语句中声明的变量?

if(z<100){
    int amount=sc.nextInt();
}

while(amount!=100)
{ //this is wrong.it says we cant find amount variable ?
    something
}

3 个答案:

答案 0 :(得分:8)

amount的范围绑定在花括号内,所以你不能在外面使用它。

解决方法是将其置于if块之外(请注意,如果if条件失败,将不会分配amount):

int amount;

if(z<100){

    amount=sc.nextInt();

}

while ( amount!=100){  }

或许您打算将while语句放在if:

if ( z<100 ) {

    int amount=sc.nextInt();

    while ( amount!=100 ) {
        // something
   }

}

答案 1 :(得分:5)

要在外部范围内使用amount,您需要在if块之外声明它:

int amount;
if (z<100){
    amount=sc.nextInt();
}

为了能够读取其值,您还需要确保在所有路径中为其分配值。您尚未显示如何执行此操作,但一个选项是使用其默认值0。

int amount = 0;
if (z<100) {
    amount = sc.nextInt();
}

或者更简洁地使用条件运算符:

int amount = (z<100) ? sc.nextInt() : 0;

答案 2 :(得分:4)

你不能,它只限于if块。要么使其范围更加可见,比如在外面声明它并在该范围内使用它。

int amount=0;
if ( z<100 ) {

amount=sc.nextInt();

}

while ( amount!=100 ) { // this is right.it will now find amount variable ?
    // something
}

检查here有关java中可变范围的内容

相关问题