gpt4 book ai didi

尝试更改变量的 Java 方法不起作用

转载 作者:行者123 更新时间:2023-12-01 21:44:05 26 4
gpt4 key购买 nike

我目前正在编写一段游戏,其中敌人( bat )的生命值应该下降,但它不起作用。

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。

谢谢,极光

最佳答案

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 中。

关于尝试更改变量的 Java 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36120590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com