gpt4 book ai didi

java - (Java RPG) if 语句中的对象构造

转载 作者:搜寻专家 更新时间:2023-11-01 02:58:09 27 4
gpt4 key购买 nike

我制作了 4 个类(法师、胭脂、战士和傻瓜),它们扩展了“角色”类。其中每一个在各自的类别中都有自己特定的战斗方法。但是,由于在 if/else 语句中仅构造了这些对象中的一个,因此 java 无法将它们识别为存在。问题是我需要在 if/else 语句之外调用特定于类的方法。我尝试先将 4 个对象初始化为 null,然后构造/覆盖它们,但是当我调用该方法时,它仍然将它们称为 null。格式有点乱,但在这里:

编辑:感谢您的反馈!

public class Rpg {
public static Warrior wplayer = null;
public static Rouge rplayer = null;
public static Mage mplayer = null;
public static Fool fplayer = null;

public static void main(String[] args){
a2 = scan.nextInt();
if (a2 == 1){
Warrior wplayer = new Warrior();
} else if (a2 == 2) {
Rouge rplayer = new Rouge();
} else if (a2 == 3) {
Mage mplayer = new Mage();
} else {
Fool fplayer = new Fool();
while (!notdone){
System.out.println("1: Arena");
System.out.println("2: Blacksmith");
System.out.println("3: Shop");
System.out.println("4: Leave town");
System.out.println("5: Save and Quit");
int choice = scan.nextInt();
if (choice == 1 && wplayer != null){
wplayer.fightEnemy();
} else if (choice == 1 && rplayer != null){
rplayer.fightEnemy();
} else if (choice == 1 && mplayer != null){
mplayer.fightEnemy();
} else {
fplayer.fightEnemy();
}
}
}
}
}

最佳答案

这些变量的范围仅限于 if/else block 内。如果你想在外部访问它,你应该执行以下操作:

Character player = null;

if (a2==1){
player = new Warrior();
} else if (a2==2){
player = new Rouge();
} else if (a2==3){
player = new Mage();
} else{
player = new Fool();
}

// by now, player was instantiated by some concrete class and you can use it

如果每个角色都实现了自己的fightEnemy() 方法,那么您可以在这里利用多态性来自动选择正确的具体方法:

 ...
if (choice==1){
// java will figure out which "Character" this really is
// then it will call the fightEnemy method for that specific "Character" type
player.fightEnemy();
}
...

关于java - (Java RPG) if 语句中的对象构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46413963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com