I coded up a class which models a stock:
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();
}
The copy-constructor looks like:
public Stock(Stock other) throws IllegalArgumentException
{
this(other.ticker, other.shares, other.purchasePrice);
}
Here are the commands I that used to test this:
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);
Output is:
BAC 100 42.22 42.22 0.00%
BAC 100 42.22 43.35 2.68%
BAC 100 42.22 42.22 0.00%
For some reason, the last value which represents the percent-gain is not copying over?
Here’s the percent-gain method btw:
public void updatePercentGain()
{
percentGain = ((latestPrice - purchasePrice) / purchasePrice) * 100;
}
Where am I going wrong?
When your
Stockconstructor runs, it initialises thelatestPricewith thepurchasePricepassed in to the constructor. Since these values are the same, the percent gain will be 0.00%.If you wish to also copy the current
latestPricein your copy constructor, you’ll have to do that too: