variable access outside of if statement

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.


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);

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;