decHungry()减少饥饿10,而incEnergy()增加能量10。我想确保饥饿水平不会超过0到负数,能量水平不会超过100。我怎么做?

protected void feed() {
    System.out.println("\nEating...");
    if (hungry <= 90 && hungry >= 0) {
        decHungry();
        incEnergy();
        System.out.println("I've just ate dumplings, my current energy state is " + energy + " and hungry state is " + hungry);
    }
    else {
        System.out.println ("I have ate enough!");
    }
}

最佳答案

在调用该函数之前,您需要确保饥饿大于或等于10并且能量小于或等于90。

if(hungry >= 10){
    decHungry();
}
if(energy <=90){
    incEnergy();
}

10-02 22:38