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

前端 未结 14 1570
别跟我提以往
别跟我提以往 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:00

    I think an idiomatic, object oriented way of doing this is to have a setHealth on the Character class. The implementation of that method will look like this:

    public void setHealth(int newValue) {
        health = Math.max(0, Math.min(100, newValue))
    }
    

    This prevents the health from going below 0 or higher than 100, regardless of what you set it to.


    Your getHealed() implementation can just be this:

    public void getHealed() {
        setHealth(getHealth() + 15);
    }
    

    Whether it makes sense for the Character to have-a getHealed() method is an exercise left up to the reader :)

提交回复
热议问题