我使用Arraylist作爲'英雄' - 基類,而戰士,法師是派生類。我想通過使用'get'方法返回每個派生類的lifePoints和attackPoints,而我得到這樣的東西(我相信它是類的hashCode)。 (i)通過調試,它顯示正確的值,但我不知道如何返回它們,所以我想到了沒有參數的構造函數 - 失敗了。Arraylist.get返回哈希代碼,而不是班級的字段
輸出:
Hero 0 is a [email protected]
Hero 1 is a [email protected]
Hero 2 is a [email protected]
Hero 3 is a [email protected]
預期輸出:
Hero 0 is a Warrier with -1 lifePoints and 5 attackPoints
Hero 1 is a Warrier with 5 lifePoints and 2 attackPoints
Hero 2 is a Magician with 12 lifePoints and 2 spellPoints
Hero 3 is a Magician with 13 lifePoints and 2 spellPoints
我的主類的半碼
for (int i=0; i<heroes.size(); ++i) {
System.out.println("Hero "+i+ " is a "+heroes.get(i));
}
我的解決思路:使用構造函數 - 失敗。
public Magician()
{
System.out.println("Magician with " + this.lifePoints +"life points and " +this.attackPoints +" spell points.");
}
這裏是所有代碼:
Hero-
abstract class Hero {
protected int lifePoints;
protected int attackPoints;
public abstract Hero attack(Hero other);
public abstract int lifePoints();
}
法師:
public class Magician extends Hero{
static int count;
Magician(int lifePoints, int attackPoints)
{
this.lifePoints = lifePoints;
this.attackPoints = attackPoints;
count++;
}
public Magician()
{
System.out.println("Magician with " + this.lifePoints +"life points and " +this.attackPoints +" spell points.");
}
@Override
public Hero attack(Hero other) {
if(other != null)
{
if(other instanceof Hero)
{
other.lifePoints /= this.attackPoints;
if(other.lifePoints <= 0)
{
return new Magician(this.lifePoints,this.attackPoints);
}
}
//Attacking ourselves - Error
if(this.equals(other))
{
System.out.println("Hero can't attack itself");
}
}
return null;
}
@Override
public int lifePoints() {
return this.lifePoints;
}
public static int getNoMagician()
{
return count;
}
}
戰士:
public class Warrior extends Hero
{
static int count;
Warrior(int lifePoints, int attackPoints)
{
this.lifePoints = lifePoints;
this.attackPoints = attackPoints;
count++;
}
public Warrior()
{
System.out.println("Warrior with " + this.lifePoints +"life points and " +this.attackPoints +" spell points.");
}
@Override
public Hero attack(Hero other) {
if(other != null)
{
//We're attacking a warrior
if(other instanceof Warrior){
((Warrior)other).lifePoints -= this.attackPoints;
}
//We're attacking a magician
if(other instanceof Magician){
((Magician)other).lifePoints -= (this.attackPoints/2);
if(((Magician)other).lifePoints <= (this.lifePoints/2))
{
return new Warrior(this.lifePoints,this.attackPoints);
}
}
//Attacking ourselves - Error
if(this.equals(other))
{
System.out.println("Hero can't attack itself");
}
}
//False
return null;
}
@Override
public int lifePoints() {
return this.lifePoints;
}
public static int getNoWarrior()
{
return count;
}
}
這是沒有toString的類的默認字符串轉換。創建一個toString或者明確地打印出來。每個人都有優點和缺點。 –
考慮重寫'toString' – bradimus
@DaveNewton Works。我真笨。謝謝! –