2012-10-09 49 views
-1

我編寫了一類車型的股票:Java的拷貝構造函數不是複製值

public Stock(String ticker, int shares, float purchasePrice) throws IllegalArgumentException 
{ 
    if(ticker == null || ticker == "" || 
     shares <= 0 || purchasePrice <= 0) 
     throw new IllegalArgumentException(Messages.enterAppropriateValues()); 

    this.ticker = ticker; 
    this.shares = shares; 
    this.purchasePrice = purchasePrice; 
    latestPrice = purchasePrice; 
    updatePercentGain(); 
} 

的拷貝構造函數的樣子:

public Stock(Stock other) throws IllegalArgumentException 
{ 
    this(other.ticker, other.shares, other.purchasePrice); 
} 

下面是用於測試的命令我這樣的:

Stock bac = new Stock("BAC", 100, 42.22f); 
    System.out.println(bac); 

    bac.setLatestPrice(43.35f); 
    System.out.println(bac); 

    Stock bacCopy = new Stock(bac); 
    System.out.println(bacCopy); 

輸出是:

BAC 100 42.22 42.22 0.00% 
    BAC 100 42.22 43.35 2.68% 
    BAC 100 42.22 42.22 0.00% 

出於某種原因,表示百分比增益的最後一個值不會被複制過來?

這裏的百分比增益法BTW:

public void updatePercentGain() 
{ 
    percentGain = ((latestPrice - purchasePrice)/purchasePrice) * 100; 
} 

我要去哪裏錯了?

+4

這是錯誤的:'ticker ==「」',而不是你想使用'ticker.equals(「」)'。 –

+0

您可以對字符串使用「==」。它的工作原理 – Haque1

+1

'43.35'這個值是如何得到的? 'BAC 80 42.22 43.35 2.68%' –

回答

3

當您的Stock構造函數運行時,它會初始化latestPrice並將purchasePrice傳遞給構造函數。由於這些值相同,百分比增益將爲0.00%。

如果您想也是當前latestPrice在你的拷貝構造函數複製,你必須做到這一點:

public Stock(Stock other) throws IllegalArgumentException 
{ 
    this(other.ticker, other.shares, other.purchasePrice); 
    this.latestPrice = other.latestPrice; 
    updatePercentGain(); 
} 
+0

謝謝,Greg!那就是訣竅 – Haque1

2

在您的實際構造函數(不是你的拷貝構造函數),你是不是在抄襲在latestPrice,你只是設置它等於當前價格:

latestPrice = purchasePrice; 

所以你的拷貝構造函數只有在通過了「42.22」,而不是「43.35」,和您的副本沒有得到latestPrice。