Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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
}
like image 331
user1808537 Avatar asked Dec 17 '25 07:12

user1808537


2 Answers

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
   }

}
like image 111
Pubby Avatar answered Dec 19 '25 22:12

Pubby


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;
like image 37
Mark Byers Avatar answered Dec 19 '25 23:12

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!