Monica
Monica

Reputation: 1599

How do I increment a variable as another is being incremented?

I am trying to create a program in Java in which a monthly service charge is to increase by $1 for every withdrawal after the 4th withdrawal (bank account program). I've tried to use a loop, but it just got stuck.

Code:

    public void monthlyProcess() {
    int w = getWithdrawals();
    if (w > 4) {
        while(w > 4) {
            serCharge++;
        }
    }
    super.monthlyProcess();
    if(bal <= MIN_BAL) {
        status = false;
    }
}

Thank you!

Upvotes: 1

Views: 260

Answers (4)

Ethan Bolker
Ethan Bolker

Reputation: 217

Why not just surcharge += w-4 ?

edit:

surcharge += Math.max(w-4,0)

Upvotes: 3

1321941
1321941

Reputation: 2180

Looks like an infinitive loop to me, but overall I don't think you need a loop altogether:

 public void monthlyProcess() {
    int w = getWithdrawals();
    if (w > 4) {
           while(w > 4) {
            serCharge++;
            w--;
         }

    }
    super.monthlyProcess();
    if(bal <= MIN_BAL) {
        status = false;
    }
}

should do it

You got the infinitive loop, as since you was doing nothing to the w variable it would always be greater then four, so the loop would never break. and if it did you would end up with a massive service charge anyway, as it will keep incrementing because of the infinitive loop

"A programmer is out getting some milk, his wife calls him and says, ' while out can you pick up some eggs'... he never returns"

Upvotes: 3

Theodore R. Smith
Theodore R. Smith

Reputation: 23259

Here, this should work.

Cheers!

public void monthlyProcess() {
    int w = getWithdrawals();
    if (w > 4) {
        serCharge += w - 4;
    }
    super.monthlyProcess();
    if(bal <= MIN_BAL) {
        status = false;
    }
}

Upvotes: 4

Alexis Pigeon
Alexis Pigeon

Reputation: 7522

The other answers so far correctly point you towards getting rid of the while loop altogether, but for completeness sake, here's a solution that will keep that loop:

public void monthlyProcess() {
    int w = getWithdrawals();
    if (w > 4) {
        while(w > 4) {
            serCharge++;
            // make sure you update the value of w, 
            // otherwise you'll be stuck in an infinite loop!
            w--; 
        }
    }
    super.monthlyProcess();
    if(bal <= MIN_BAL) {
        status = false;
    }
}

Upvotes: 1

Related Questions