I am trying to access variable outside an if statement in java. The variable is axeMinDmg
. Here is what i have but getting an error. I want minDmg = axeMi
Just declare the integer outside the if statement:
int minDmg;
if(weapon.equals("axe")){
minDmg = axeMinDmg;
} else {
System.out.println();
System.out.println("Can access variable: " + minDmg);
You'll need to define the variable outside of the if statement to be able to use it outside.
In Java, variables are defined within a scope. Here the scope is the if block. so if you declare it outside the if block, it will be available in the enclosing method scope.
If you want to assign a variable to outside of if-else block, you can use ternary operator which represented by the :
operator.
For example, the standard if-else Java expression:
int money;
if (shouldReceiveBonus()) {
price = 100;
}
else {
price = 50;
}
With ternary operator is equivalent to:
int money = shouldReceiveBonus() ? 100 : 50;