feed方法java if-statement

时间:2014-03-31 21:09:10

标签: java if-statement methods

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!"); 
    }
}

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

最简单的方法可能是在末尾添加一个检查,看看你是否超出了界限,如果是这样,就把自己带回界限。

if(hungry<0)hungry=0;
if(energy>100)energy=100;

答案 2 :(得分:0)

您应该在调用方法decHungryincEnergy后检查。如果饥饿或能量水平超过限制,则将它们设置为限制值:

protected void feed() {
    System.out.println("\nEating...");

    decHungry();
    incEnergy();

    if (hungry < 0)
        hungry = 0;

    if (energy > 100)
        energy = 100;

    // ...
}