Search code examples
javasubtraction

How do you make a function that subtracts 2 values but will make value "a" not go beneath 0?


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

Solution

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