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. 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.
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
. 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;
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.