public int attack(Bear bear)
{
int newStamina=bear.getStamina() - 50;
bear.setStamina(newStamina);
return bear.getStamina();
}
To extend on my fabulous Bear class, I’ve decided to implement an attack(!) method.
I have 2 instances of my bear object: Bear1 and Bear2.
In my head:
Bear1.attack(Bear2);
then my code gets Bear2 current stamina value and takes away 50 from it, assigning it to the newStamina variable.
Bear2 then gets passed this new stamina variable with the setStamina method.
I then return Bear2‘s current stamina, after the brutal bear attack.
This works, sort of. But I imagine there’s a far better way.
Anyhoo. What I would like to do is, after:
int newStamina=bear.getStamina() - 50;
is:
if(newStamina <= 0)
{
// the bear is dead!
}
Now my method attack returns an int, because if the bear doesn’t die, it still has HP and I would like to output this current HP to the console or where ever.
If the bear is out of stamina, then I need to return something that signifies this.
What would you do? I can’t return false, and I’m not sure that would work anyway.
A good rule of thumb is only modify instance variables inside set methods. Doing this will keep your code more manageable.