Java购买方法
这是我的家庭作业。 我正在尝试写一个“买入”方法,允许以给定的价格买入股票中的一些股票。该方法采用两个参数:股票数量作为整数,每股价格作为双精度。 例如:Java购买方法,java,casting,Java,Casting,这是我的家庭作业。 我正在尝试写一个“买入”方法,允许以给定的价格买入股票中的一些股票。该方法采用两个参数:股票数量作为整数,每股价格作为双精度。 例如: 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 shar
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
// 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
public class Stock{
private int noOfShares = 0;
}
我的代码:
public static void buy(int numBuyShares, double priceBuyShares )
{
double tempTotalCost = ((double)numBuyShares * priceBuyShares);
sell
方法的份额和成本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
// 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
public class Stock{
private int noOfShares = 0;
}
1.)我如何使用以前的股份减去新价格和股份法
numShares
显式转换为double。隐式自动装箱将处理它,因为已经有双变量priceShares
-将使用双算术double
作为键确实不好,所以我会创建一些股票类。因此,您的HashMap
的键可以是包含价格的股票
对象,int是您拥有的上述股票的数量
HashMap stocks=newhashmap()代码>
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
// 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
public class Stock{
private int noOfShares = 0;
}
然后在buy方法中,您需要添加一行,将刚购买的股票数量添加到其中:
noOfShares += numBuyShares;
按照封装原则,要从类外部访问此变量,需要一个get方法,即:
public int getNoOfShares(){
return noOfShares;
}
谢谢我是这里的新手。作业的价格部分使用
double
?因为它确实不理想……我注意到的第一件事是:检查变量名。麻木股票!=numShares,priceBuyShares!=价格共享是的,双倍价格是分配的一部分。double
用作整数和大多数整数数学的表示,但您可能会遇到难看的舍入错误:总成本也是如此?是的,唯一的区别是总成本将是双倍。我可以在我的股票类中写这个吗:private Queue StockList=new LinkedList();我可以在我的购买方法中编写此代码吗?股票新闻股票=新股(numBuyShares、priceBuyShares);股票列表。添加(新闻股票);我认为最好使用地图,因为你可能想买2股,然后再决定买4股。在一张地图中,你会尝试它已经包含了你正在购买的股票,如果它包含了,那么只需增加你地图中的数量。