我有一种方法可以使用ArrayQueue实现来计算股票市场程序的资本损益。
但是我需要递归调用此方法,以便正确计算资本。
示例:队列中有3个采购交易(对象)。100股每股10美元,150股每股20美元和50股每股30美元。但是现在我只想出售275股,每股价格为25美元。
这是我计算资本的方法:
public static int calculateCapital(Transaction sale,
Transaction purchase, ArrayQueue q) {
int sharesRemaining = 0;
int capital = 0;
//if shares to be sold is less that the shares in the next transaction
if (sale.getShares() < purchase.getShares()) {
//calculate the capital
capital = capital + (sale.getShares()*sale.getPrice())-
(sale.getShares()*purchase.getPrice());
// return the remaining shares to the queue
purchase.setShares(purchase.getShares()-sale.getShares());
q.enqueue(purchase);
//if shares to be sold are more than the shares in the next transaction
} else if (sale.getShares() > purchase.getShares()) {
//calculate the capital
capital = capital + (sale.getShares()*sale.getPrice())-
(sale.getShares()*purchase.getPrice());
//store the remaining share count needed to be sold
sharesRemaining = sale.getShares() - purchase.getShares();
sale.setShares(sharesRemaining);
Transaction nextPurchase = (Transaction)q.dequeue();
while (sharesRemaining > 0) {
// RECURSIVELY CALL CALCULATECAPITAL METHOD
calculateCapital(sale, nextPurchase, q);
}
//if shares to be sold are equal to the shares in the next transaction
} else if (sale.getShares() == purchase.getShares()) {
//calculate the capital
capital = capital + (sale.getShares()*sale.getPrice())-
(sale.getShares()*purchase.getPrice());
}
return capital;
}
当我运行客户端测试程序时,我收到一个错误消息,说当队列去下一个事务时,该队列为空,这是因为我没有将相同的队列传递给递归调用,而是将其传递给了空队列。
有没有办法将输入到原始方法调用中的相同Queue传递到递归方法中?喜欢calculateCapital(sale, nextPurchase, this.q);
吗?
您的代码有两个问题-最大的问题是您不想使用while
循环来进行递归方法调用。sharesRemaining
例如,如果为10,它将永远保持不变(它是局部变量)。您要做的是使用一条if
语句并添加方法调用的结果。q.dequeue();
在检查是否还有任何其他内容之前,您还需要先调用,然后sharesRemaining
将其移到if
语句中。
// more code above this, but...
/* you do not want to use sale.getShares() as this is a decrementing value
as the method is called recursively. you want to know the purchase price
for the number of shares in this transaction using the purchase price and
sale price. use a double instead of int to calculate cents */
double salePrice = purchase.getShares() * sale.getPrice();
double purchasePrice = purchase.getShares() * purchase.getPrice();
// calculate the capital, only for this transaction
double capital = salePrice - purchasePrice;
// store the remaining share count needed to be sold, this is passed into the method
// and why it should not be used to calculate the capital
sale.setShares(sale.getShares() - purchase.getShares());
// If we have more shares, call the method to process the next one.
if (sale.getShares() > 0) {
// Get the next transaction
Transaction nextPurchase = (Transaction)q.dequeue();
// Add this value to the value of the "next" transaction, recursively
capital += calculateCapital(sale, nextPurchase, q);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句