【问题标题】:Java method that tries to change a variable isn't working尝试更改变量的 Java 方法不起作用
【发布时间】:2016-03-20 22:47:59
【问题描述】:

我目前正在编写一个游戏的代码,其中一个敌人(一只蝙蝠)的生命值应该会下降,但它不起作用。

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 class variables methods


【解决方案1】:

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封装这种行为。

【讨论】:

  • 非常感谢!我花了 30 分钟试图理解这个通过引用传递的东西,但是给出的例子太复杂了!
猜你喜欢
  • 2017-06-19
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
相关资源
最近更新 更多