Source of 10.16.java


  1: public void buy(int sharesBought, double pricePerShare)
  2: {
  3:    StockPurchase purchase = new StockPurchase(sharesBought, pricePerShare);
  4:    ledger.addToBack(purchase);
  5: } // end buy
  6: 
  7: public double sell(int sharesSold, double pricePerShare)
  8: {
  9:    double saleAmount = sharesSold * pricePerShare;
 10:    double totalCost = 0;
 11: 
 12:    while (sharesSold > 0)
 13:    {
 14:       StockPurchase transaction = ledger.removeFront();
 15:       double shareCost = transaction.getCostPerShare();
 16:       int numberOfShares = transaction.getNumberOfShares();
 17: 
 18:       if (numberOfShares > sharesSold)
 19:       {
 20:          totalCost = totalCost + sharesSold * shareCost;
 21:          int numberToPutBack = numberOfShares - sharesSold;
 22:          StockPurchase leftOver = new StockPurchase(numberToPutBack, shareCost);
 23:          ledger.addToFront(leftOver); // Return leftover shares
 24:          // Note: Loop will exit since sharesSold will be <= 0 later
 25:       }
 26:       else
 27:          totalCost = totalCost + numberOfShares * shareCost;
 28:          
 29:       sharesSold = sharesSold - numberOfShares;
 30:    } // end while
 31: 
 32:    return saleAmount - totalCost; // Gain or loss
 33: } // end sell