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

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


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


just add 15 to the health, so:

health += 15;if(health > 100){    health = 100;}

However, as bland has noted, sometimes with multi-threading (multiple blocks of code executing at once) having the health go over 100 at any point can cause problems, and changing the health property multiple times can also be bad. In that case, you could do this, as mentioned in other answers.

if(health + 15 > 100) {    health = 100;} else {    health += 15;}


You don't need a separate case for each int above 85. Just have one else, so that if the health is already 86 or higher, then just set it directly to 100.

if(health <= 85)    health += 15;else    health = 100;