2013-10-04 117 views
0

我有一些代碼來看一個類,我理解它的大部分,但我很困惑這種方法。使用給定的代碼,返回變化總是不會導致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; 

回答

3

按順序執行語句。計算後,對totalGiventotalOfItems的更改不會更改change

+0

對,但是因爲我們在要求編譯器返回更改之前將totalGiven和totalOfItems更改爲0,是不是會返回0? – user2769212

+0

@ user2769212'change'不是兩個變量的函數,它是一個常量,它是在計算變量值時計算出來的。 –

+0

好吧,我想我現在明白了。改變現在它自己的變量,它等於原來的this.totalGiven - this.totalOfItems;因此,重置this.totalGiven和this.totalOfItems而不影響更改是可以的。對? – user2769212

0

對於這一點:

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

第一你一個(非零)值賦給change然後重置原始變量,然後才返回change值。變量值被複制到另一個變量,然後重置。

+0

我希望我能理解你剛剛所說的話......我想你在第一行中說的是:「雙變= this.totalGiven-- this.totalOfItems;」 「totalGiven」和「totalOfItems」確實代表了不同的totalGiven和totalOfItems。我認爲我需要重新命名它們或者其他東西,但是現在這樣做有一定意義。 – user2769212

+0

這些語句只是按順序執行。這真的很簡單。 'return change;'返回已有的'change'值。 –

0

我認爲的假設是,在某些時候,receivePayment和scanItem已經被調用,所以他們將字段變量重新賦值爲非零的數字。然後給出改變。在您已經計算出更改後,您將重置下次交易的變量,交易關閉。

相關問題