需要幫助弄清楚如何打印個人硬幣,如宿舍= 3,便士= 1,而不是給我4個硬幣76美分。我嘗試設置4個計數器,但只是反覆打印出硬幣名稱和答案是錯誤的。遞歸幣改變
import java.util.Scanner;
public class Money
{
public static void main(String args[])
{
int[] coins = { 1, 5, 10, 25};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Change (In Cents): ");
int sum = scan.nextInt();
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
String quarter = "";
Money minCoin = new Money();
System.out.println(minCoin.findMinCoins(coins, sum, counter1, counter2, counter3, counter4));
System.out.println(counter4);
}
private int findMinCoins(int[] coins, int sum, int counter1, int counter2, int counter3, int counter4)
{
if (sum <= 0 || coins.length == 0)
{
return 0;
}
for (int i = coins.length - 1; i >= 0; i--)
{
if(coins[i] == 1 && coins[i] != 5)
{
counter1++;
}
if(coins[i] == 5)
{
counter2++;
}
if(coins[i] == 10)
{
counter3++;
}
if(coins[i] == 25)
{
counter4++;
}
if (coins[i] <= sum)
{
System.out.println("Pennies: " + counter1);
System.out.println("Nickels: " + counter2);
System.out.println("Dimes: " + counter3);
System.out.println("Quarters: " + counter4);
return 1 + findMinCoins(coins, sum - coins[i], counter1, counter2, counter3, counter4);
}
}
return 0;
}
}
在您的退貨聲明中,您有1 + findMinCoins ...但這並不真正提供關於1表示什麼樣的硬幣的信息。相反,嘗試向return語句中的變量添加1,例如:findMinCoins(coins,sum - coins [i],counter1 + 1,...)以表明您需要另一個便士 –