0

我有一些代码要查看一个类,我理解其中的大部分内容,但对这种方法感到困惑。使用给定的代码,返回更改不会总是导致 0,因为最后输入的是 totalOfItems 和 totalGiven 为 0.0。有人告诉我,运行它时不会发生,但我想了解原因。谁能帮我?

 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;
4

3 回答 3

3

语句按顺序执行。计算后更改totalGiventotalOfItems不会更改change

于 2013-10-04T18:07:18.257 回答
0

为了这:

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

首先为 分配一个(非零)值change然后重置原始变量,然后才返回 的值change。变量值被复制到另一个变量,然后重置。

于 2013-10-04T18:08:34.367 回答
0

我认为的假设是,在某些时候,receivePayment 和 scanItem 已经被调用,因此它们将字段变量重新分配给一个不为零的数字。然后给出改变。在您为下一个交易重置变量后,交易会在您计算完更改后关闭。

于 2013-10-04T18:11:17.733 回答