【问题标题】:How do i make set a maximum for a variable?如何为变量设置最大值?
【发布时间】:2018-03-18 11:48:10
【问题描述】:

我如何设置最大数量,以使某个变量不能超过我的代码中的限制,玩家可以反复去治疗,因此他们的健康变得超过他们的最大生命值

public class HEAL {
    public static int maxhp = 25;
    public static int hp = 10;

    public static void main(String[] args) throws IOException {
        heal();
    }

    public static void heal() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Would you like me to heal you? \n[1] Yes\n[2]No");
        int choice = Integer.parseInt(br.readLine());
        if (choice == 1) { 
            System.out.println("You have been healed for 10 hp");
            HEAL.hp = HEAL.hp + 10;
            System.out.println("Your current HP: "+HEAL.hp);
        }
        else if (choice == 2) {
            System.out.println("Leave");
        } 
    }
}

【问题讨论】:

  • 你在这方面真的尝试过吗?

标签: java netbeans int limit


【解决方案1】:

我要做的是创建一个函数 setHp,它会检查它是否在约束范围内。

if (val < 0 || val > 100) {
     /* not within constraints, do what you want here */
  } else {
  hp = val;
}

【讨论】:

    【解决方案2】:

    首先,将变量 hp 设为私有,其次,在对象内部处理是否以及何时增加它。 这个

    [1]

    private static int hp=10;
    

    [2]

    public incrementHealPoints(int _hp){
      if(this.hp < HEAL.maxhp){
        this.hp += _hp;
      }else{
        // just ignore? maybe raise an error or log this?
      }
    }
    

    【讨论】:

      【解决方案3】:

      试试这个(添加if以检查hp是否超过25):

      HEAL.hp=HEAL.hp+10;
      if (HEAL.hp>25) //add this in your code
      HEAL.hp=25;
      System.out.println("Your current HP: "+HEAL.hp);
      

      如果变量 hp 超过 25,则将其值设置为 25(因为 25 是 最大限制)。

      【讨论】:

        【解决方案4】:

        使用Math.min:

        HEAL.hp = Math.min(HEAL.hp + 10, 25)
        

        25 是最大生命值。

        【讨论】:

          【解决方案5】:

          我在 cmets 的正确行中添加了一些解释:

          if((HEAL.hp + 10) >= HEAL.maxhp) { // If HEAL.hp after adding 10 would be equal or greater than HEAL.maxhp...
              HEAL.hp = HEAL.maxhp; // Assign HEAL.maxhp value (it's 25 in your example) to HEAL.hp
          } else { // Otherwise...
              HEAL.hp = HEAL + 10; // Add 10 to HEAL.hp
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-03-10
            • 1970-01-01
            • 1970-01-01
            • 2018-01-01
            • 2019-08-05
            • 1970-01-01
            • 2016-01-05
            • 1970-01-01
            相关资源
            最近更新 更多