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
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 );