user2769212
user2769212

Reputation: 21

Method (correctly) declares variables as 0 but I don't understand why?

I have some code to look at for a class and I understand most of it, but am confused about this method. With the given code, wouldn't the return change always result in 0 since the last thing put in was that the totalOfItems and the totalGiven are 0.0. I was told that when running it that won't happen but I'd like to understand why. Can anyone help me?

 public SelfCheckout () {
 this.totalOfItems = 0.0;
 this.totalGiven = 0.0;
 }

 /**
  * This method will scan the item.
 * @param amount The amount the items cost.
 */

public void scanItem (double amount){
this.totalOfItems = this.totalOfItems + amount;
}

/** The method will add the items scanned and return the total due.
 * 
 * @return getTotalDue The getTotalDue is the total amount of items scanned.
 */
public double getTotalDue(){
    return this.totalOfItems;
}

/** The method will show the amount that is received from the consumer.
 * 
 */
public void receivePayment(double amount){
    this.totalGiven = this.totalGiven + amount;
}

/**The method will calculate the amount of change due.
 * 
 */
public double produceChange(){
    double change = this.totalGiven - this.totalOfItems;
    this.totalGiven = 0.0;
    this.totalOfItems = 0.0;
    return change;

Upvotes: 0

Views: 62

Answers (3)

ford prefect
ford prefect

Reputation: 7388

The assumption I think is that at some point receivePayment and scanItem have already been called so they reassign the field variables to a number that is not zero. Then change is given. The transaction is closed after you have already computed change you reset the variables for the next transaction.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272307

For this:

double change = this.totalGiven - this.totalOfItems;
this.totalGiven = 0.0;
this.totalOfItems = 0.0;
return change;

first you assign a (non-zero) value to change, then you reset the original variables, and only then return the value of change. The variable values are copied to another variable and then reset.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182779

Statements execute in order. Changes to totalGiven and totalOfItems won't change change after it has been computed.

Upvotes: 3

Related Questions