我目前正在对游戏进行编码,其中一个敌人(一只蝙蝠)应该有健康下降,但它不起作用。
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;
}
我无法理解为什么smallknifeMA不会降低变量bat1.health。
谢谢, 极光
答案 0 :(得分:3)
Java不是通过引用传递的。此
Abilities.smallknifeMA(bat1.health);
需要更新bat1.health
。像,
bat1.health = Abilities.smallknifeMA(bat1.health);
或者,修改smallknifeMA
以获取Bat
参数并直接更新health
。像,
static void smallknifeMA(Bat bat) {
bat.health -= 2.0;
}
然而,让您的班级成员public
成为一种不好的做法;你应该在Bat
中封装这种行为。