开发者

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?


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

}


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


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.


encapsulate the field and put a check in setter method.

int a;

void setA(int a){
   if value not in range throw new IllegalArgumentException();
}


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).


public void setHealth(int newHealth) {
  if(newHealth >= 0 && newHealth <= 100) {
    _health = newHealth;
  }
}


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜