Search code examples
javamathintlimit

Setting a limit to an int value


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?


Solution

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