0

I am having troubles incrementing the value of my instance variables. I tried making a method so that for every pet I buy, it will add that much to how many I already have. But when I print dogs variable, it says 0 even though I added 2. I'd appreciate any help. Thanks!

public class myStuff static int dogs; static int cats;

public static void main(String[] args) {
    myStuff.buy(dogs, 2);
    System.out.println(dogs);

}
public static void buy(int pet, int howMany) {
    pet = pet + howMany;
}

}

Niko
  • 123
  • 1
  • 7

2 Answers2

0

you cant do that in java, since it is pass-by-value

0

In Java, method parameters are passed by value (which means the value of dogsin your case is passed in the first Place, but never touched). Objects however, are manipulated by reference. So, if you want to increase the number of pets, you could use a class Pet with a value count

public class Pet {
    private int count;

    public Pet(int count) {
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

If you then pass an instance of Pet to your buy function and increase the count via setCount, the value will be saved.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
David3103
  • 125
  • 10