我需要將遞回包含在我的最終專案中。有人建議我簡單地將我的一個回圈更改為遞回方法。這是我到目前為止所擁有的。它每次都回傳 0 值。
public static double GetCostTotal(Liquor[] inv, int index) {
if ( index >= inv.length) return 0;
else return GetCostTotal(inv, index 1);
}
這是我在主方法中呼叫它的地方:
//beer. regular 1d array
System.out.println("\nNow for beer. How many beers are you taking inventory of?: ");
int sizeBeers = keyboard.nextInt();
Beer[] invBeers = new Beer[sizeBeers];
for (int i = 0; i < invBeers.length; i ) {
invBeers [i] = new Beer();
System.out.println("Enter product name: ");
invBeers [i].setLiquorName(keyboard.next());
System.out.println("Enter the count: ");
invBeers [i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost: ");
invBeers [i].setLiquorCost(keyboard.nextDouble());
}
//calls GetCostTotal method and passes invBeers array
double beerCost = GetCostTotal(invBeers, sizeBeers);
System.out.println("The total cost of the beer inventory is: $" beerCost);
我仍在努力尋找自己的解決方案,但顯然也在尋求你們的幫助。謝謝!
uj5u.com熱心網友回復:
只需將當前專案的總成本和遞回呼叫的結果相加:
public static double GetCostTotal(Liquor[] inv, int index) {
if (index >= inv.length) return 0;
else return (inv.getLiquorCount() * inv.getLiquorCost()) GetCostTotal(inv, index 1);
}
注意:這不是尾遞回,無論如何,Java 不會優化尾呼叫,所以如果你的陣列太長,你會得到一個 StackOverflowError。
如果您修改它以使用累加器,如 hfontanez 的答案,并用一種??語言和平臺上進行適當的尾呼叫消除,它不會溢位。希望有一天 Java 會增加 TCO/TCE。
uj5u.com熱心網友回復:
你的遞回方法應該是這樣的:
public static double GetCostTotal(Liquor[] inv, int index, double total) {
if (index >= inv.length)
return total;
else
total = inv[index].amount() * inv[index].cost();
return GetCostTotal(inv, index 1, total);
}
您可以看到這total是傳遞給函式的引數,以便您可以有效地累積成本總和。否則,您將在每次呼叫時覆寫金額。其次,else子句正在執行必要的計算。
最后,您的初始呼叫觸發了默認(基本)情況,因為您傳遞的是陣列的長度而不是從零開始。
double beerCost = GetCostTotal(invBeers, 0, 0);
由于您的遞回呼叫遞增index1,因此您需要為 傳遞零,index為total.
如果你這樣做,你應該得到正確的結果。這是我的示例輸入和結果:
Now for beer. How many beers are you taking inventory of?:
3
Enter product name:
Bud
Enter the count:
1
Enter the cost:
2
Enter product name:
Miller
Enter the count:
2
Enter the cost:
3
Enter product name:
Michelob
Enter the count:
3
Enter the cost:
4
The total cost of the beer inventory is: $20.0
您可以看到,第一次迭代的累積成本為 2.00 (1 2),第二次為 6.00 (2 3),最后一次為 12.00 (3*4),總共為 20.00 (2 6 12)
注意:我為Beer而不是傳統類創建了一個 Java 記錄。這就是我呼叫的方法GetCostTotal是cost()and 的原因amount()。你需要改變他們以符合您的正確的方法名稱或更改Liquor,并Beer為Java的記錄,如果你使用的是最新的Java,我強烈推薦。
uj5u.com熱心網友回復:
解決方法在這里。沒有執行必要的計算并且錯誤地呼叫了該方法。
public static double GetCostTotal(Liquor[] inv, int index, double totalCost) {
if ( index >= inv.length) return totalCost;
else totalCost = inv[index].getLiquorCount()*inv[index].getLiquorCost();
return GetCostTotal(inv, index 1, totalCost);
}
double beerCost = GetCostTotal(invBeers, 0, 0);
System.out.println("The total cost of the beer inventory is: $" beerCost);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/380768.html
