imgolden62
imgolden62

Reputation: 426

Variable does not increment in probability program

I have three classes. A super class probability, a subclass Eating and a runner class Person.

The goal is for certain methods to be "triggered" when conditions are met in a for loop. Eating (method dox) will increase the variable weight. Once weight is greater than 120, then the probability (int px) of dox being called decreases and the probability (py) of exercising increases until weight drops below a threshold.

However my int px NEVER decreases. Why is this? Below are my decrease probability methods and the trigger that calls them.

public void Trigger()
{
    if (weight >= 120)
    {
        dProb(px);
        dProb(pz);
        iProb(py);
    }
    if (weight <= 80)
    {
        dProb(py);
        iProb(px);
        iProb(pz);
    }


public void dProb(int p)
{
    p -= 5;
} 
public void iProb (int p)
{
    p += 5;
} 

Upvotes: 1

Views: 127

Answers (1)

Maroun
Maroun

Reputation: 95968

p is a local variable for the method dProb, and it's a different variable than p in iProb. Meaning that px, pz and py are not affected (Java passes by value, always).

When you enter the method, a temporary variable is created, and will be destroyed as soon as you exit it.

You should make p a class member (read more here), or let the methods return the result, and assign it to the caller, or directly modify px, py and pz.

Upvotes: 3

Related Questions