Java Buy method

怎甘沉沦 提交于 2020-01-07 08:08:34

问题


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);
  1. How do I write a proper code if I want to multiply Integer by Double? Am I doing this the right way?

  2. 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:


  1. That way of multiplying a double and an integer will work fine.

  2. 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:


  1. There no need for explicit casting of numShares to double. The implicit auto-boxing will take care of it, as there's already double variable priceShares - double arithmetic will be used.

  2. 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 use double as a key there so, I would create some Stock class. So the key of your HashMap can the Stock 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!