gpt4 book ai didi

java - 如何让我的程序计算调用方法的次数?

转载 作者:行者123 更新时间:2023-11-30 04:24:46 25 4
gpt4 key购买 nike

好吧,我正在自学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);
}
}
}
  • 扎克

最佳答案

你不能在方法之外创建一个像计数器这样的全局变量吗?有点像这样。

public class testThingy {
public static int counter = 0;
/* main method and other methods here */
}

只需在每次调用该方法时(在您想要计数的方法内)将计数器加 1,它就会更新全局变量。

关于java - 如何让我的程序计算调用方法的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com