我使用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。我真笨。谢谢! –