Search code examples
javadice

Adding a number to a fixed max number


I have searched and searched for this but I cannot find a question about it anywhere. In my code I wish to add a number to another number but it cannot exceed the starting value. I am working with a Dice program so, say I roll a 6 and my starting value was at 40. (It is a D&D type game, so one person attacks and then they lose health etc) So when this occurs, say my health at this point is 36, my starting health was 40, and I roll a 6 to heal myself for 6 HP, but I cannot heal for 6 I can only heal for 4. How would I set this up so the number when added does not exceed 40 HP?

int maxhealth = 40;

defenderD6 = m6.roll();

This is an example of what I am using, a starting int and then an object that will roll a number between 1-6.

Thank you


Solution

  • You can take :

    Math.min(maxhealth, newHealth);
    

    if your new health is 36 + 6 = 42, it will take 40.