-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

如果您还希望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;

因此,您的复制构造函数仅传递“42.22”而不是“43.35”,并且您的副本没有获得最新价格。

于 2012-10-09T03:51:26.213 回答