Accumulator
Accumulator

Reputation: 903

Java: object cannot be resolved to a variable

my object apparently can't be resolved to a variable...

In Game.Java:

public static void main(String[] args) {
    Slime slime = new Slime();
}

In Player.Java:

public static void Attack() {
    System.out.println("Player attacks!");
    int dmg = ATTACK;
    System.out.println(dmg + " damage to Slime!");
    slime.HP -= dmg;
    System.out.println(Player.HP);
}

So how do I take dmg off of slime's HP? I've done some research, this still isn't making sense.

Upvotes: 1

Views: 1607

Answers (1)

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15180

Player.java needs to either have a reference to slime, or it needs to be passed in through the Attack() method. The second makes more sense, actually.

public void attack(Slime opponent) {
    int dmg = ATTACK;
    opponent.HP -= dmg;
}

This will allow you to "attack" multiple different slimes.

The alternative would be to store a reference to the slime in the Player class itself:

public class Player {
    private Slime slime;
    private static final int ATTACK = 10; // or something

    public void setSlime(Slime slime) {
        this.slime = slime;
    }

    public void attack() {
        int dmg = ATTACK;
        slime.HP -= dmg;
    }
}

Effectively, unless you give Player some way of knowing about the Slime instance, it can't affect that Slime instance.

I did notice that you were using mostly static methods, but here I've used class variables and non-static methods for OOP purposes.

Also, Java coding convention is that method calls should have lower case names, which is why I've preferred attack() to Attack().

Upvotes: 2

Related Questions