株式をモデル化するクラスをコード化しました。
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%
何らかの理由で、パーセントゲインを表す最後の値がコピーされていませんか?
ところで、パーセントゲイン法は次のとおりです。
public void updatePercentGain()
{
percentGain = ((latestPrice - purchasePrice) / purchasePrice) * 100;
}
どこが間違っていますか?