简体   繁体   中英

How can I use a variable that declared in an if statement outside the if?

How can I use a variable that I declared inside an if statement outside the if block?

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

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

The scope of amount is bound inside the curly braces and so you can't use it outside.

The solution is to bring it outside of the if block (note that amount will not get assigned if the if condition fails):

int amount;

if(z<100){

    amount=sc.nextInt();

}

while ( amount!=100){  }

Or perhaps you intend for the while statement to be inside the if:

if ( z<100 ) {

    int amount=sc.nextInt();

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

}

In order to use amount in the outer scope you need to declare it outside the if block:

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

To be able to read its value you also need to ensure that it is assigned a value in all paths. You haven't shown how you want to do this, but one option is to use its default value of 0.

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

Or more concisely using the conditional operator:

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

you cant, its only confined to the if block.either make its scope more visible, like declare it outside if and use it within that scope.

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

amount=sc.nextInt();

}

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

check here about variable scopes in java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM