[英]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.
使用给定的代码,返回的变化不会总是导致0,因为最后输入的是totalOfItems和totalGiven为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. 计算
change
后,对totalGiven
和totalOfItems
更改将不会更改。
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
. 首先,您分配一个(非零)值进行
change
, 然后重置原始变量,然后才返回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. 我认为的假设是,在某个时候已经调用了receivePayment和scanItem,因此它们将字段变量重新分配为不为零的数字。 Then change is given.
然后给出变化。 The transaction is closed after you have already computed change you reset the variables for the next transaction.
在您已经计算了更改并重置下一个事务的变量之后,该事务将关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.