earnest
earnest

Reputation: 261

variable access outside of if statement

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 = axeMinDmg. thanks

    @SuppressWarnings("unused")
    public static void main(String[] args)
        throws IOException
        {


            int count = 1;

    // start both with 1 point  
    int goodTotal = 50;
    int monTotal = 50;

    // set amount of money that Goodman has
    int moneyAmt = 10;




    // setting array for bat

    int [] bat = {2, 4, 3};
    int batMinDmg = bat[0];
    int batMaxDmg = bat[1];
    int batCost = bat[2];

    //setting array for axe
    int [] axe = {4, 6, 6};
    int axeMinDmg = axe[0];
    int axeMaxDmg = axe[1];
    int axeCost = axe[2];

    //setting array for sword

    int [] sword = {6, 8, 10};
    int swordMinDmg = sword[0];
    int swordMaxDmg = sword[1];
    int swordCost = sword[2];



   // ask if Goodman would like to purchase a weapon   
   System.out.println("Would you live to purchase a weapon (YES OR NO): ");
   Scanner sc = new Scanner(System.in);
   String name = sc.next();


   if (name.equals("yes")){
       System.out.println("Select Your Weapon \n axe \n bat \n sword : \n  ");

       Scanner wc = new Scanner(System.in);
       String weapon = wc.next();
       int minDmg = axeMinDmg;

    if(weapon.equals("axe")){
     int minDmg = axeMinDmg;
   } else {
       System.out.println();
} // close if statement    

Upvotes: 7

Views: 32932

Answers (5)

ranjeetsingh
ranjeetsingh

Reputation: 1

int minDmg = 0; // outside of if statement.

Hii, I had same problem with if statement and after this i solved my problem. in this problem you have to declare the variable outside the loop and if statement and this this null value at the time of initialise.

int minDmg = 0;

Upvotes: -1

Johnny
Johnny

Reputation: 15423

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;

Upvotes: 2

fastcodejava
fastcodejava

Reputation: 41097

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.

Upvotes: 5

Lucas Zamboulis
Lucas Zamboulis

Reputation: 2551

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

Upvotes: 2

Femaref
Femaref

Reputation: 61467

You'll need to define the variable outside of the if statement to be able to use it outside.

Upvotes: 9

Related Questions