SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Classes
Exercise:
Exercises
Question:8 | ISBN:9780136091813 | Edition: 2

Question

Add the following method to the Stock class:
public void clear()
Resets this Stock’s number of shares purchased and total cost to 0.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// 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

 

0 0

Discussions

Post the discussion to improve the above solution.