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

Java 如何在if之外使用if语句中声明的变量?,java,Java,如何使用在if块外的if语句中声明的变量 if(z<100){ int amount=sc.nextInt(); } while(amount!=100) { //this is wrong.it says we cant find amount variable ? something } if(z您不能,它仅限于if块。或者使其范围更可见,例如在if外部声明它,并在该范围内使用它 int amount=0; if ( z<100 ) { amount=sc.

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

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

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

if(z您不能,它仅限于if块。或者使其范围更可见,例如在if外部声明它,并在该范围内使用它

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

amount=sc.nextInt();

}

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

如果(z要在外部范围内使用
金额
,您需要在
if
块外声明它:

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

如果(zamount
的范围绑定在大括号内,因此不能在大括号外使用

解决方案是将其带出if块(注意,如果if条件失败,
amount
将不会被分配):

int金额;

if(zLearn more about variable scope:这实际上不起作用,因为变量的数量并不总是赋值的,其他答案更好。@EdC如果不理解OP的问题,很难说什么“实际”起作用。希望这个答案能说明问题。
int amount = 0;
if (z<100) {
    amount = sc.nextInt();
}
int amount = (z<100) ? sc.nextInt() : 0;
int amount;

if(z<100){

    amount=sc.nextInt();

}

while ( amount!=100){  }
if ( z<100 ) {

    int amount=sc.nextInt();

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

}