Add the following method to the Stock class:
public void clear()
Resets this Stock’s number of shares purchased and total cost to 0.
// package classes;
public class Stock {
private String symbol;
private int totalShares;
private double totalCost;
// initializes a new Stock with no shares purchased
public Stock(String symbol) {
this.symbol = symbol;
totalShares = 0;
totalCost = 0.0;
}
// crate constructor to set total shares and total cost
public Stock(String symbol, int totalShares, int totalCost) {
this.totalCost = totalCost;
this.totalShares = totalShares;
this.symbol = symbol;
}
// returns the total profit or loss earned on this stock
public double getProfit(double currentPrice) {
double marketValue = totalShares * currentPrice;
return marketValue - totalCost;
}
// records purchase of the given shares at the given price
public void purchase(int shares, double pricePerShare) {
totalShares += shares;
totalCost += shares * pricePerShare;
}
// implemnting the clear method
// by calling this method on stock object it'll set total shares and cost to zero
public void clear() {
this.totalShares = 0;
this.totalCost = 0;
}
public static void main(String args[]) {
Stock stock = new Stock("bull",430,43000);
System.out.println("total stocks and price before calling clear method: " +stock.totalShares+ ", " +stock.totalCost);
stock.clear();
System.out.println("total stocks and price after calling clear method: " +stock.totalShares+ ", " +stock.totalCost);
}
}
Output:
total stocks and price before calling clear method: 430, 43000.0
total stocks and price after calling clear method: 0, 0.0