我有一些代碼來看一個類,我理解它的大部分,但我很困惑這種方法。使用給定的代碼,返回變化總是不會導致0,因爲最後一件事是totalOfItems和totalGiven是0.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;
對,但是因爲我們在要求編譯器返回更改之前將totalGiven和totalOfItems更改爲0,是不是會返回0? – user2769212
@ user2769212'change'不是兩個變量的函數,它是一個常量,它是在計算變量值時計算出來的。 –
好吧,我想我現在明白了。改變現在它自己的變量,它等於原來的this.totalGiven - this.totalOfItems;因此,重置this.totalGiven和this.totalOfItems而不影響更改是可以的。對? – user2769212