Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a limit to an int value

Tags:

java

int

math

limit

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?

like image 949
Stan Avatar asked Apr 21 '11 19:04

Stan


1 Answers

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

}
like image 143
RoflcoptrException Avatar answered Oct 12 '22 20:10

RoflcoptrException