简体   繁体   中英

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;

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM