-3

I want to subtract the Value of food from the value of hunger but hunger is not allowed to ge below 0. How would I achieve that ? Also I code in Java

public void eat(Food food) {
        
        if (this.hunger > 0 && food.getTyp() == "Dogfood") {
            hunger = hunger - food.getVolume();
            
        }
        
    }

1 Answers1

0
public void eat(Food food) {
    if ("Dogfood".equals(food.getTyp())) {
        hunger = hunger - food.getVolume();
        hunger = hunger < 0 ? 0 : hunger;
    }
}

Like this, every time the value of hunger is set to a new value, the new value is calculated. Then, if hunger < 0, it is set to 0. Also, I changed your equals method according to one of the comments.

Andreas
  • 344
  • 4
  • 14