问题
This is my home work. I am trying to write a method 'buy' that allows some shares of the stock to be bought at a given price. The method takes two arguments: a number of shares as an int, and a price per share as a double. For example:
Stock myStock = new Stock("FCS");
myStock.buy(20, 3.50); // buys 20 shares at $3.50
// myStock now has 20 shares at total cost $70.00
myStock.buy(10, 2.00); // buys 10 shares at $2.00
// myStock now has 30 shares at total cost $90.00
My Code :
public static void buy(int numBuyShares, double priceBuyShares )
{
double tempTotalCost = ((double)numBuyShares * priceBuyShares);
How do I write a proper code if I want to multiply Integer by Double? Am I doing this the right way?
I would like to accumulate the cost and shares, so how do I write this? Because I need to use the shares and cost for a
sell
method.
Thank you all . Now I need to write a 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
1.) How do i use the previous shares to minus of the new price and the shares method?
回答1:
That way of multiplying a double and an integer will work fine.
To accumulate total shares you need a variable in the Stock class to keep track. For example:
public class Stock{ private int noOfShares = 0; }
Then in the buy method you need to add a line to add the number of shares just bought to it:
noOfShares += numBuyShares;
Following encapsulation principles, to access this variable from outside the class, you will need a get method, ie:
public int getNoOfShares(){ return noOfShares; }
回答2:
There no need for explicit casting of
numShares
to double. The implicit auto-boxing will take care of it, as there's already double variablepriceShares
- double arithmetic will be used.To save the number and price of your stock, you will have to use some kind of structure. I am thinking
HashMap
perhaps. But it's really not good to usedouble
as a key there so, I would create some Stock class. So the key of yourHashMap
can theStock
object containing price and the int is the number of said stocks in you possession.HashMap<Stock, int> stocks = new HashMap<Stock, int>();
来源:https://stackoverflow.com/questions/21660916/java-buy-method