Source of 7.16.java


  1: // @author Frank M. Carrano, Timothy M. Henry
  2: // @version 5.0
  3: public void buy(int sharesBought, double pricePerShare)
  4: {
  5:    StockPurchase purchase = new StockPurchase(sharesBought, pricePerShare);
  6:    ledger.addToBack(purchase);
  7: } // end buy

  9: public double sell(int sharesSold, double pricePerShare)
 10: {
 11:    double saleAmount = sharesSold * pricePerShare;
 12:    double totalCost = 0;

 14:    while (sharesSold > 0)
 15:    {
 16:       StockPurchase transaction = ledger.removeFront();
 17:       double shareCost = transaction.getCostPerShare();
 18:       int numberOfShares = transaction.getNumberOfShares();

 20:       if (numberOfShares > sharesSold)
 21:       {
 22:          totalCost = totalCost + sharesSold * shareCost;
 23:          int numberToPutBack = numberOfShares - sharesSold;
 24:          StockPurchase leftOver = new StockPurchase(numberToPutBack, shareCost);
 25:          ledger.addToFront(leftOver); // Return leftover shares
 26:          // Note: Loop will exit since sharesSold will be <= 0 later
 27:       }
 28:       else
 29:          totalCost = totalCost + numberOfShares * shareCost;
 30:          
 31:       sharesSold = sharesSold - numberOfShares;
 32:    } // end while

 34:    return saleAmount - totalCost; // Gain or loss
 35: } // end sell