好的,我正在自学java,我正在尝试编写一个递归方法,可以计算它被调用/使用的次数。到目前为止,这是我的代码:
public class FinancialCompany
{
public static void main(String[] args)
{
StdOut.println("Enter your monthly investment: ");
double money= StdIn.readDouble();
double total = Sum(money);
Months();
StdOut.printf("you have reached an amount of $%8.2f", total);
StdOut.println();
}
public static double Sum(double money)
{
double total = (money * 0.01) + money;
if(total >= 1000000)
{
return total;
}
else
{
total =(money * 0.01) + money;
return Sum(total);
}
}
public static int counter = 0;
public static void Months()
{
counter++;
StdOut.println("It should take about " + counter + " month(s) to reach your goal of $1,000,000");
}
}
这是输出:
Enter your monthly investment: 1000 (I chose 1000)
It should take about 1 month(s) to reach your goal of $1,000,000
you have reached an amount of $1007754.58
每次我运行它都会打印出最终数量,但我希望它告诉我到达那里需要多少个月,但它打印出来的只是 1 个月。任何帮助将不胜感激!
**
完成代码(感谢大家的贡献!)
**
public class FinancialCompany
{
public static int counter = 0;
public static void main(String[] args)
{
StdOut.println("Enter your monthly investment: ");
double money= StdIn.readDouble();
double investment = money;
double total = Sum(money, investment);
StdOut.println("It should take about " + counter + " month(s) to reach your goal of $1,000,000");
}
public static double Sum(double money, double investment)
{
counter++;
double total = (money * 0.01) + money;
if(total >= 1000000)
{
return total;
}
else
{
return Sum(total + investment ,investment);
}
}
}
- 扎克