-1

株式をモデル化するクラスをコード化しました。

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;
}

どこが間違っていますか?

4

2 に答える 2

3

コンストラクターが実行されると、コンストラクターに渡されたStockで初期化されます。これらの値は同じなので、パーセント ゲインは 0.00% になります。latestPricepurchasePrice

コピー コンストラクターでcurrent もコピーする場合latestPriceは、それも行う必要があります。

public Stock(Stock other) throws IllegalArgumentException
{
    this(other.ticker, other.shares, other.purchasePrice);
    this.latestPrice = other.latestPrice;
    updatePercentGain();
}
于 2012-10-09T03:50:42.843 に答える
2

実際のコンストラクター (コピー コンストラクターではない) では、latestPrice をコピーするのではなく、現在の価格に等しく設定するだけです。

latestPrice = purchasePrice;

したがって、コピー コンストラクターは「43.35」ではなく「42.22」のみを渡し、コピーは latestPrice を取得しません。

于 2012-10-09T03:51:26.213 に答える