Fixing methods in Java OOP

蹲街弑〆低调 提交于 2019-12-06 04:48:05
Hovercraft Full Of Eels

In my print statements while I execute the program, they do not update the health correctly like they should.

Your health field is a static field and thus a field of the class not of the instance. Every Dragon will share the exact same health value, which is not what you want. I suggest:

  • First make more classes as you shouldn't have all this code within Dragon. You should create a Warrior class as well, one that represents the person fighting the Dragon, one that should have his own health and similar fields.
  • Most all the fields and methods here should be non-static. The only exception that I can see should be the main method, and that's it. Please read Why are static variables considered evil?
  • I would get all user interface code out of my Warrior and Dragon classes, and instead have them focus only on maintaining their own state (field values) and behaviors (methods).
  • Use another class for user interaction. If simple, this could all be in the main method, but this type of code does not "scale" well.
  • Also a nitpick, but never use == true or == false, but instead use more succinct and easily readable code that just tests the boolean variable or expression itself. So instead of if (foo == true) and if (bar == false) do if (foo) and if (!bar).

For example:

class Creature {
    private int health;
    private int attack;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health < 0 ? 0 : health;
    }

    public int getAttack() {
        return attack;
    }

    public void setAttack(int attack) {
        this.attack = attack;
    }

    public boolean isAlive() {
        return health > 0;
    }

}

class Dragon extends Creature {
    // add Dragon specific methods
}

class Warrior extends Creature {
    // add Warrier specific methods
}

I think you want to change

public static int getDamage()
{
    Random generator = new Random();
    int attack = generator.nextInt(10) + 1;
    health = health - dragonAttack;
    return attack;
}

To:

 public static int getDamage()
{
    Random generator = new Random();
    setAttack(generator.nextInt(10) + 1);
    health = health - dragonAttack;
    return attack;
}

And similarly for getDragonDamage... You are setting a local variable (int this case attack) and expecting it to be updated in getDragonDamage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!