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

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

    I would make a static method in a helper class. This way, rather than repeating code for every value which need to fit within some boundaries, you can have one all purpose method. It would accept two values defining the min and max, and a third value to be clamped within that range.

    class HelperClass
    {
        // Some other methods
    
        public static int clamp( int min, int max, int value )
        {
            if( value > max )
                return max;
            else if( value < min )
                return min;
            else
                return value;
        }
    }
    

    For your case, you would declare your minimum and maximum health somewhere.

    final int HealthMin = 0;
    final int HealthMax = 100;
    

    Then call the function passing in your min, max, and adjusted health.

    health = HelperClass.clamp( HealthMin, HealthMax, health + 15 );
    

提交回复
热议问题