user1808537
user1808537

Reputation: 19

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
}

Upvotes: 2

Views: 179

Answers (3)

Pubby
Pubby

Reputation: 53057

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
   }

}

Upvotes: 8

Mark Byers
Mark Byers

Reputation: 838566

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;

Upvotes: 5

PermGenError
PermGenError

Reputation: 46428

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

Upvotes: 4

Related Questions