简体   繁体   English

如何两次运行父母方法

[英]How to run a parents method twice

I'm Making a game which uses a parent to run an attack class as shown below 我正在制作一个使用父级来运行攻击类的游戏,如下所示

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!";
}

I have multiple different weapons which i want to use and have succeded in this however i have a dagger which i would like to attack twice per turn instead of once like the others. 我有多种想要使用的武器,并且已经成功使用过,但是我有一把匕首,我想每回合攻击两次,而不是像其他武器一样攻击一次。 This is the class which i use to set the daggers damage values: 这是我用来设置匕首伤害值的类:

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);
}

I then have a class that runs it and currently it does this: 然后,我有一个运行它的类,当前它可以这样做:

    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;
    }

Instead of it printing the attack twice, i want it to attack twice on the same line. 我希望它在同一行上两次攻击,而不是两次打印攻击。 I was wondering what i can change in the dagger class which would allow me to do so. 我想知道我可以在匕首类中进行哪些更改,以便我可以这样做。 Any help is of course appreciated thank you! 任何帮助,当然感谢,谢谢!

This answer is an explanation of @Arnav 's comments. 此答案是@Arnav的评论的解释。 Here Dagger is a sub-class of the main weapon class and you want to invoke super-class' attack twice when the attack method of Dagger is called. 这里的Dagger是主要weapon类的子类,您想在调用Dagger的攻击方法时两次调用超类的attack

For this you need to call super.attack twice from Dagger attack method: 为此,您需要通过Dagger攻击方法两次调用super.attack

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
}

Note: I deleted my earlier answer, because this approach is better than the other one. 注意:我删除了先前的答案,因为这种方法比其他方法更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM