Source of StockLedger.java


  1: /**
  2:    A class that records the purchase and sale of stocks,
  3:    and provides the capital gain or loss.
  4:    
  5:    @author Frank M. Carrano
  6:    @author Timothy M. Henry
  7:    @version 4.0
  8: */
  9: public class StockLedger
 10: {
 11:   private QueueInterface<StockPurchase> ledger;
 12:   
 13:   public StockLedger()
 14:   {
 15:     ledger = new LinkedQueue<>();
 16:   } // end default constructor
 17:   
 18:   /** Records a stock purchase in this ledger.
 19:       @param sharesBought   The number of shares purchased.
 20:       @param pricePerShare  The price per share. */
 21:   public void buy(int sharesBought, double pricePerShare)
 22:   {
 23:     while (sharesBought > 0)
 24:     {
 25:       StockPurchase purchase = new StockPurchase(pricePerShare);
 26:       ledger.enqueue(purchase);
 27:       sharesBought--;
 28:     } // end while
 29:   } // end buy
 30:   
 31:   /** Removes from this ledger any shares that were sold 
 32:       and computes the capital gain or loss.
 33:       @param sharesSold     The number of shares sold.
 34:       @param pricePerShare  The price per share.
 35:       @return  The capital gain (loss). */
 36:   public double sell(int sharesSold, double pricePerShare)
 37:   {
 38:     double saleAmount = sharesSold * pricePerShare;
 39:     double totalCost = 0;
 40:     
 41:     while (sharesSold > 0)
 42:     {
 43:       StockPurchase share = ledger.dequeue();
 44:       double shareCost = share.getCostPerShare();
 45:       totalCost = totalCost + shareCost;
 46:       sharesSold--;
 47:     } // end while
 48:     
 49:     return saleAmount - totalCost; // Gain or loss
 50:   } // end sell
 51: } // end StockLedger