Austin Loach
Austin Loach

Reputation: 3

How do I change the value of a variable from another class and still be able to change it within the other class?

So I'm fairly new with programming having done it for maybe just under a year at this point. I'm even more new with Java (I did C++ before). So I have variables like numberHealthPotions, health, attackDamage, and so on, in a class named Fighting. But then in my main class, there are points in the game in which the character picks up a weapon, picks up a potion, or is wounded. I just need a way to say in my main class he was wounded then change the value of the health of the character or whatever.

This is just a snipet of my code to give you an idea...

else if(inputHKitchen.equalsIgnoreCase ("examine")){
                System.out.println("Examine what?");
                examineWhat = in.nextLine();
                if(examineWhat.equalsIgnoreCase("drawer")){
                    System.out.println("\tYou found a knife!");
                    attackDamage = 50;
                    System.out.println("\tYour attack damage has been increased!\n");
                    System.out.println(houseKitchen);
                }

Upvotes: 0

Views: 70

Answers (2)

Phil Freihofner
Phil Freihofner

Reputation: 7910

I would write a series of public methods for the character that manage these various values.

For example, in the class YourCharacter:

private int attackDamage;

public void addDamage(int value)
{
    attackDamage += value;
}

Then in your snippet:

if (examineWhat.equalsIgnoreCase("drawer")){
    yourCharacter.addDamage(50);
}

Lots of good game-writing advice for Java can be found at java-gaming.org

Upvotes: 1

DJ-ST
DJ-ST

Reputation: 129

If your variable is static, then it might be

//note this variable must be public or protected
Player.HEALTH = 0;

if its not static, then

Player p = new Player();
p.HEALTH = 0;

Upvotes: 1

Related Questions