2016-03-20 117 views
0

我目前正在編寫一個遊戲,其中一個敵人(蝙蝠)應該使其健康下降但不起作用。嘗試更改變量的Java方法無法正常工作

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。

感謝, 極光

+1

也許提供一些有關什麼不工作的信息。你有沒有嘗試在調試器中查看發生了什麼? – dman2306

回答

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中封裝這個行爲

+0

非常感謝!我花了30分鐘試圖通過參考來理解這個過程,但是給出的例子太複雜了! –