我編寫了一類車型的股票: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;
}
我要去哪裏錯了?
這是錯誤的:'ticker ==「」',而不是你想使用'ticker.equals(「」)'。 –
您可以對字符串使用「==」。它的工作原理 – Haque1
'43.35'這個值是如何得到的? 'BAC 80 42.22 43.35 2.68%' –