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

use*_*537 2 java

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

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

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

Pub*_*bby 8

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

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

int amount;

if(z<100){

    amount=sc.nextInt();

}

while ( amount!=100){  }
Run Code Online (Sandbox Code Playgroud)

或许你打算将while语句放在if里面:

if ( z<100 ) {

    int amount=sc.nextInt();

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

}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 5

amount在外部作用域中使用,您需要在if块外声明它:

int amount;
if (z<100){
    amount=sc.nextInt();
}
Run Code Online (Sandbox Code Playgroud)

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

int amount = 0;
if (z<100) {
    amount = sc.nextInt();
}
Run Code Online (Sandbox Code Playgroud)

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

int amount = (z<100) ? sc.nextInt() : 0;
Run Code Online (Sandbox Code Playgroud)