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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With