简体   繁体   English

feed方法java if-statement

[英]feed method java if-statement

decHungry() decreases hungry by 10 and incEnergy() increases energy by 10. I would like to make sure it does not go past 0 in hungry levels to negative numbers and does not go above 100 in energy levels. decHungry()减少饥饿10点, incEnergy()将能量增加10点。我想确保它在饥饿水平上没有超过0到负数,并且在能量水平上不会超过100。 How do I do that? 我怎么做?

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

Before calling the function you want to make sure that hungry is greater than or equal to 10 and that energy is less than or equal to 90. 在调用函数之前,您需要确保饥饿大于或等于10且能量小于或等于90。

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

The simplest way would probably be to add a check at the end to see if you went out of bounds, and if so return yourself to the bounds. 最简单的方法可能是在末尾添加一个检查,以查看是否超出界限,如果是这样,则将自己返回界限。

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

You should check for that after calling the methods decHungry and incEnergy . 你应该调用方法decHungryincEnergy 检查incEnergy If the hungry or energy level exceeds the limits, then set them to the limit value: 如果饥饿或能量水平超过限制,则将它们设置为限制值:

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

    decHungry();
    incEnergy();

    if (hungry < 0)
        hungry = 0;

    if (energy > 100)
        energy = 100;

    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM