How can I increment a variable without exceeding a maximum value?

前端 未结 14 1559
别跟我提以往
别跟我提以往 2021-01-30 12:03

I am working on a simple video game program for school and I have created a method where the player gets 15 health points if that method is called. I have to keep the health at

相关标签:
14条回答
  • 2021-01-30 13:02

    I would just do this. It basically takes the minimum between 100 (the max health) and what the health would be with 15 extra points. It ensures that the user's health does not exceed 100.

    public void getHealed() {
        health = Math.min(health + 15, 100);
    }
    

    To ensure that hitpoints do not drop below zero, you can use a similar function: Math.max.

    public void takeDamage(int damage) {
        if(damage > 0) {
            health = Math.max(health - damage, 0);
        }
    }
    
    0 讨论(0)
  • 2021-01-30 13:07
    health = health < 85 ? health + 15 : 100;
    
    0 讨论(0)
提交回复
热议问题