Reputation: 19
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
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
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
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