I want to set a limit to an int
value I have in Java. I'm creating a simple health system, and I want my health to stay between 0 and 100. How can I do this?
I would recommend that you create a class called Health and you check every time if a new value is set if it fulfills the constraints :
public class Health {
private int value;
public Health(int value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException();
} else {
this.value = value;
}
}
public int getHealthValue() {
return value;
}
public void setHealthValue(int newValue) {
if (newValue < 0 || newValue > 100) {
throw new IllegalArgumentException();
} else {
value = newValue;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With