我需要显示名称,种类名称,生命值和强度。除物种名称以外,所有内容都会打印为空。有什么想法吗?
这是我的主班
if (species.equals("b") || species.equals("B")) {
Creature balrog = new Creature(name, strength, hit);
players.add(balrog);
System.out.println("Current Players: ");
System.out.println("NAME | SPECIES | STRENGTH | HIT POINTS");
for (int i = 0; i < players.size(); i++) {
System.out.println(players.get(i).toString());
}
}
这是在我的生物课上,它将打印所有内容
public String toString() {
String result = name;
result += " | ";
result += species;
result += " | ";
result += strength;
result += " | ";
result += hitPoints;
result += "\n";
return result;
}
最后是Balrog类,生物的子类
Balrog(String name, int strength, int hit){
super(name,strength,hit);
}//ends Balrog constructor
String getSpecies(){
return "Balrog";
}
没有错误消息,它只是在物种名称应该出现的地方打印出空值。
最佳答案
您正在创建超类而不是子类的实例
Creature balrog = new Creature(name, strength, hit);
应该
Creature balrog = new Balrog(name, strength, hit);
您还需要在toString中获取子类的种类
public String toString() {
String result = name;
result += " | ";
result += getSpecies();
result += " | ";
result += strength;
result += " | ";
result += hitPoints;
result += "\n";
return result;