0

This is my homework

I am tring to write method sell that allows some shares of the stock to be sold at a given price. The method takes two arguments: a number of shares as an int, and a price per share as a double. The method returns a boolean value to indicate whether the sale was successful. For example:

// myStock now has 30 shares at total cost $90.00
boolean success = myStock.sell(5, 4.00);
// sells 5 shares at $4.00 successfully
// myStock now has 25 shares at total cost $70.00
success = myStock.sell(2, 5.00);
// sells 2 shares at $5.00 successfully
// myStock now has 23 shares at total cost $60.00  

My Code :

public static void buy(int numBuyShares, double priceBuyShares)
{
double tempTotalCost = ((double)numBuyShares * priceBuyShares);
totalShares += numBuyShares;
totalCost += priceBuyShares;

}
public static void sell(int numSellShares, double priceSellShares) 
{

 ?????
}

1.) How do I use the previous buy shares and cost to minus the sell stock and price ?

  • `totalShares -= numBuyShares;` ? – AlexR Feb 09 '14 at 16:35
  • Have you made any attempt at all? Right now it doesn't look like you have anything more than your previous question. http://stackoverflow.com/questions/21660916/java-buy-method – Jeroen Vannevel Feb 09 '14 at 16:35
  • Why would one store the total cost of all shares, if the price per share can change? – Mads T Feb 09 '14 at 16:37
  • My bad. I am writing a multi-Thread class program. I need to do a buy method , sell method and profit method. The price and shares of both methods will be generate randomly at the Thread class. – newbie_Roy Feb 09 '14 at 16:41

1 Answers1

0

I'd imagine you want something like this...

public static boolean sell(int numSellShares, double priceSellShares) {
    double sellCost = numSellShares * priceSellShares; // calculate total $
                                                        // to sell

    // assure 2 things:
    // shares to sell does not exceed total # of shares; and
    // total $ to sell does not exceed total cost
    if (numSellShares <= totalShares && sellCost <= totalCost) {
        // subtract #shares and cost from total
        totalShares -= numSellShares;
        totalCost -= sellCost;
        return true; // return success
    }
    // tried to sell more shares or $ than what exists
    else {
        return false; // return failure
    }
}

but then again, no idea what your requirements are so cannot say for sure what determines success or failure.

Max Seo
  • 196
  • 6