Setting a limit to an int value

2019-04-01 01:15发布

问题:

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?

回答1:

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

}


回答2:

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


回答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.



回答4:

encapsulate the field and put a check in setter method.

int a;

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


回答5:

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



回答6:

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


回答7:

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

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