variable access outside of if statement

前端 未结 4 1805
南方客
南方客 2020-12-02 00:39

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

相关标签:
4条回答
  • 2020-12-02 01:11

    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);
    
    0 讨论(0)
  • 2020-12-02 01:12

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

    0 讨论(0)
  • 2020-12-02 01:23

    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.

    0 讨论(0)
  • 2020-12-02 01:27

    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;
    
    0 讨论(0)
提交回复
热议问题