我一直为null
出现一个Elf 1
的对象,该对象应该显示BEST FRIEND: HOBBIT 2
,但只显示null
。我试图寻找解决方案,但没有任何帮助。谁能帮我找出解决方案吗?谢谢。
示例输出:
ELF 1 [ STATUS: Alive Elf ] [ CLAN: Forest | BEST FRIEND: null ] [ STR: 5 | DEX: 7 | ARM: 1 | MOX: 16 ] [ COINS: 77 | HEALTH: 80 ]
ELF 2 [ STATUS: Alive Elf ] [ CLAN: City | BEST FRIEND: HOBBIT 1 ] [ STR: 14 | DEX: 20 | ARM: 18 | MOX: 12 ] [ COINS: 1000 | HEALTH: 80 ]
主班
// HOBBIT 1 AND 2
System.out.println("\nLet's create new two Hobbits!");
System.out.println("Building two new hobbits...");
System.out.println("\nHobbit 1 name: ");
String hobbitName = sc.nextLine();
Hobbit hobbit1 = new Hobbit(hobbitName);
System.out.println("Hobbit 2 name: ");
String hobbitName2 = sc.nextLine();
Hobbit hobbit2 = new Hobbit(hobbitName2, 8, 12, 2, 14, 10, 30);
System.out.println("\n" + hobbit1);
System.out.println(hobbit2);
// ELF 1 AND 2
System.out.println("\nLet's create new two Elves!");
System.out.println("Building two new Elves...");
System.out.println("\nElf 1 name: ");
String elfName1 = sc.nextLine();
Elf elf1 = new Elf(elfName1);
System.out.println("Elf 2 name: ");
String elfName2 = sc.nextLine();
Elf elf2 = new Elf(elfName2, 14, 20, 18, 12, 1000, 80, "Forest", hobbit1);
System.out.println("\n" + elf1);
System.out.println(elf2);
精灵类中的代码
public class Elf extends Humanoid {
private final String clan;
private String bestFriend;
public Elf(String name) {
super(name);
// randomly sets clan
Random random = new Random();
if(random.nextBoolean()){
clan = "Forest";
} else {
clan = "City";
}
}
public Elf(String name, String clan, Hobbit bestFriend) {
super(name);
this.clan = clan;
this.bestFriend = bestFriend.getName();
}
public Elf(String name, int strength, int dexterity, int armour, int moxie, int coins, int healthRating, String clan, Hobbit bestFriend) {
super(name, strength, dexterity, armour, moxie, coins, healthRating);
this.clan = clan;
this.bestFriend = bestFriend.getName();
}
public String getBestFriend() {
return this.bestFriend;
}
public void setBestFriend(Hobbit bestFriend) {
this.bestFriend = bestFriend.getName();
}
public String getClan() {
return clan;
}
// only for elf 2 line
@Override
public String toString() {
return getName() +
" [ STATUS: " + super.isAlive() +
" Elf ] [ CLAN: " + clan +
" | BEST FRIEND: " + getBestFriend() +
" ]" + super.toString();
}
}```
答案 0 :(得分:2)
您要调用构造函数Elf(String)
来创建elf1;这个构造函数设置氏族和名称,仅此而已。没有什么可以设置“最好的朋友”的,因此它保持为空。