8

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?

Pops
  • 30,199
  • 37
  • 136
  • 151
Stan
  • 3,659
  • 14
  • 35
  • 42

7 Answers7

13

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

}
kiedysktos
  • 3,910
  • 7
  • 31
  • 40
RoflcoptrException
  • 51,941
  • 35
  • 152
  • 200
  • Thanks, it worked out exactly the way I wanted. (Can't click the accept button yet, have to wait 6 more minutes.) – Stan Apr 21 '11 at 19:28
  • 1
    `IllegalArgumentException` is what you typically want to use for illegal arguments like this. Methods that model the things you want to do in a game (like adding or removing X health without going beyond the boundaries) are key on a class like this too. – ColinD Apr 21 '11 at 19:32
  • Yes you could also use IllegalArgumentException instead of a custom HelathException. – RoflcoptrException Apr 21 '11 at 19:33
  • I would use the setHeathValue within the Constructor so it doesn't have to be wrote twice, but besides that, its all good. – WORMSS Mar 18 '13 at 13:38
  • I wouldn't do that since you shouldn't call overridable methods in the constructor. – RoflcoptrException Mar 18 '13 at 14:09
  • now you can refactor this so the "if" part is extracted to external method. DRY :) – kiedysktos Sep 01 '16 at 09:44
  • also, I would do renaming work here: variable "value" to "health" and do appropriate renaming with setter and getter. – kiedysktos Sep 01 '16 at 10:06
6

Use a getter/setter model.

public class MyClass{
    private int health;

    public int getHealth(){
        return this.health;
    }

    public int setHealth(int health){
        if(health < 0 || health > 100){
            throw new IllegalArgumentException("Health must be between 0 and 100, inclusive");
        }else{
            this.health = health;
        }
    }
}
Kyle Sletten
  • 5,365
  • 2
  • 26
  • 39
3

I'd create a class that enforces that.

public class Health {
  private int health = 100;

  public int getHealth() {
    return health;
  }

  // use this for gaining health
  public void addHealth(int amount) {
    health = Math.min(health + amount, 100);
  }

  // use this for taking damage, etc.
  public void removeHealth(int amount) {
    health = Math.max(health - amount, 0);
  }

  // use this when you need to set a specific health amount for some reason
  public void setHealth(int health) {
    if (health < 0 || health > 100)
      throw new IllegalArgumentException("Health must be in the range 0-100: " + health);
    this.health = health;
  }
}

This way if you have an instance of Health, you know for a fact that it represents a valid amount of health. I imagine that you'd typically want to just use methods like addHealth rather than setting the health directly.

ColinD
  • 108,630
  • 30
  • 201
  • 202
1

encapsulate the field and put a check in setter method.

int a;

void setA(int a){
   if value not in range throw new IllegalArgumentException();
}
kdabir
  • 9,623
  • 3
  • 43
  • 45
0

There is no way to limit a primitive in Java. The only thing you can do is to write a wrapper class for this. Of course by doing this you lose the nice operator support and have to use methods (like BigInteger).

Landei
  • 54,104
  • 13
  • 100
  • 195
0
public void setHealth(int newHealth) {
  if(newHealth >= 0 && newHealth <= 100) {
    _health = newHealth;
  }
}
jtahlborn
  • 52,909
  • 5
  • 76
  • 118
-3

No point in creating a special class. To increment i, use this:

public void specialIncrement(int i) { if(i<100) i++ }