Reputation: 53
I am currently coding this bit of a game in which, an enemy (a bat) should have its health drop but it's not working.
class BatTest{
public static void main(String args[]) {
String input = "";
boolean exit = false;
Bat bat1 = new Bat();
Inventory MainInv = new Inventory();
MainInv.smallknife = true;
System.out.println("A bat has appeared!");
System.out.println("Health: " + bat1.health + " Attack Strength: " + bat1.damage);
do{
System.out.println("Health: " + bat1.health + " Attack Strength: " + bat1.damage);
System.out.print("What would you like to do: ");
input = Keyboard.readString();
if (input.equalsIgnoreCase("Attack")) {
Abilities.smallknifeMA(bat1.health);
System.out.println(bat1.health);
}
else if (input.equalsIgnoreCase("exit")) {
exit = true;
}
}while(!exit);
}
}
//enemyH denotes the health of the enemy
class Abilities {
static double smallknifeMA(double enemyH) {
enemyH = enemyH - 2.0;
return enemyH;
}
}
class Inventory {
boolean smallknife;
boolean startlockerkey;
}
I can't really understand why smallknifeMA doesn't lower the variable bat1.health.
Thanks, Aurora
Upvotes: 0
Views: 60
Reputation: 201399
Java is not pass by reference. This
Abilities.smallknifeMA(bat1.health);
needs to update bat1.health
. Something like,
bat1.health = Abilities.smallknifeMA(bat1.health);
Or, modify smallknifeMA
to take a Bat
argument and update the health
directly. Something like,
static void smallknifeMA(Bat bat) {
bat.health -= 2.0;
}
However, it is a bad practice to make your class members public
; you should probably encapsulate this behaviour in Bat
.
Upvotes: 3