如何运行父方法两次

时间:2016-09-03 11:57:57

标签: java inheritance methods

我制作一个使用父母来运行攻击类的游戏,如下所示

public String attack(int damage, int extradamage, String type) {

    int hitpossibility;

    hitpossibility = (int) ((Math.random() * 100) + 1);
    if (type.compareTo("Ranged") == 0) {
        weaponnoise = "twang!";

    }else{
    weaponnoise = "swing!";
    }

    if (chancetohit >= hitpossibility) {
        for (int x = 0; x < damage; x++) {
            result = result + (int) ((Math.random() * 6) + 1);
        }
        result = result + extradamage;
         return weaponnoise + " The " + name + " did " + +result + " damage";


    }
    return weaponnoise +"The " +name+" missed!";
}

我有多种不同的武器我想使用并且已经成功了但是我有一把匕首,我想每回合攻击两次,而不是像其他一样。这是我用来设置匕首伤害值的类:

public class Dagger extends Blade {

public Dagger() {
    super();
    damage = 1;
    extradamage = -1;
    chancetohit = 75;
}

public String attack(int damage, int extradamage, String type) {

    return super.attack(damage, extradamage, type);
}

然后我有一个运行它的类,目前它执行此操作:

    for (int l = 0; l < 2; l++) {
        System.out.println(pointy.attack(pointy.damage, pointy.extradamage, pointy.getType()));
        monsterhealth = monsterhealth - pointy.result;
        System.out.println(monsterhealth);
        pointy.result = 0;
    }

而不是将攻击打印两次,我希望它在同一条线上进行两次攻击。我想知道我能在匕首课上改变什么才能让我这样做。 任何帮助当然值得感谢谢谢!

1 个答案:

答案 0 :(得分:2)

这个答案是对@Arnav评论的解释。这里Dagger是主weapon类的子类,并且当调用attack的攻击方法时,您希望两次调用超类“Dagger”。

为此,您需要从super.attack攻击方法两次致电Dagger

public class Dagger extends Blade {

public Dagger() {
super();
damage = 1;
extradamage = -1;
chancetohit = 75;
}

public String attack(int damage, int extradamage, String type) {
   String result1 = super.attack(damage, extradamage, type);
   String result2 =super.attack(damage, extradamage, type);
   return // You can return result1 or result2 based on your requirement
}

注意:我删除了我之前的答案,因为这种方法比另一种更好。