【问题标题】:How to call out method with parameter?( Java )如何调用带参数的方法?(Java)
【发布时间】:2018-10-14 18:48:23
【问题描述】:

我正在完成教科书上的任务。我不能从同一个类中调用“poisonAttack”方法。如果有人能给我反馈,将不胜感激。

public class PoisonMatango   extends Matango {
    PoisonMatango  pm = new PoisonMatango ('A');


    public PoisonMatango ( char suffix) {
        super(suffix);


    }
    // The method I am trying call.
    public void  poisonAttack(Hero h) {
        super.attack(h);
        int poisonCount = 5;
        if ( poisonCount >=0 ) {
            System.out.println("The enemy had spread poisonous pollons");
            int pollenDamage = h.hp / 5;
             h.hp-= pollenDamage;
            System.out.println("Hero has received " + pollenDamage + "damage from " );
            poisonCount --;
        }else
        {
            System.out.println("No additional attack were made since poisonCount= 0");
        }}

    }

【问题讨论】:

标签: java


【解决方案1】:

您必须使用创建的类对象“pm”来调用方法并根据方法定义传递所需的参数。您的代码具有 Hero 类的 Object 类型参数

pm.poisonAttack(hr);

以下是上述代码的解决方案:-

// 解决方案中用作参数的类对象 公共类英雄 {

int hp = 100;

}

// 超类 公共类 Matango {

Hero a;

public Matango(Hero suffix) {
    this.a =suffix;
}

// Super Class Method 
public void attack(Hero h){
    System.out.println("\n\nHero hp var value::"+h.hp);
}

}

// PoisonMatango

public class PoisonMatango   extends Matango {


    public PoisonMatango ( Hero suffix) {
        super(suffix);


    }
    // The method I am trying call.
    public void  poisonAttack(Hero h) {
        super.attack(h);
        int poisonCount = 5;
        if ( poisonCount >=0 ) {
            System.out.println("The enemy had spread poisonous pollons\n");
            int pollenDamage = h.hp / 5;
             h.hp-= pollenDamage;
            System.out.println("Hero has received " + pollenDamage + "damage from \n" );
            poisonCount --;
        }else
        {
            System.out.println("No additional attack were made since poisonCount= 0 \n");
        }}


    public static void main(String args[])
    {
        // Create Object of Param class, this example passes object but we can pass simple data type as per method definition.
        Hero hr = new Hero();
        PoisonMatango  pm = new PoisonMatango (hr);

        pm.poisonAttack(hr);

    }

    }

【讨论】:

  • OUTPUT:= Hero hp var value::100 敌人散布有毒花粉 英雄受到 20 点伤害
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 2020-01-26
  • 2016-03-08
  • 2013-12-17
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多