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!");
}
}发布于 2014-04-01 05:17:40
在调用该函数之前,您需要确保greater大于或等于10,并且能量小于或等于90。
if(hungry >= 10){
decHungry();
}
if(energy <=90){
incEnergy();
}发布于 2014-04-01 05:11:27
最简单的方法可能是在结尾处添加一个检查,以查看您是否超出了边界,如果是,则返回到边界。
if(hungry<0)hungry=0;
if(energy>100)energy=100;发布于 2014-04-01 05:12:23
您应该在调用decHungry和incEnergy方法之后进行检查。如果饥饿或能量级别超过限制,则将其设置为限制值:
protected void feed() {
System.out.println("\nEating...");
decHungry();
incEnergy();
if (hungry < 0)
hungry = 0;
if (energy > 100)
energy = 100;
// ...
}https://stackoverflow.com/questions/22772224
复制相似问题