我有一种方法可以使用ArrayQueue实现来计算股票市场计划的资本收益/损失。
但我需要递归调用此方法才能正确计算资本。
实施例: 我在队列中有3个购买交易(对象)。 100股每股10美元,150股每股20美元,50股每股30美元。但现在我想以每股25美元的价格出售275股。
这是我计算资本的方法:
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);
一样?
答案 0 :(得分:1)
您的代码存在两个问题 - 最大的问题是您不希望使用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);
}