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

标签 java recursion

好吧,我正在自学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/

相关文章:

java - JUnit 测试未能测试 system.out.println 结果

java - 通过键盘激活 JButton

java - 如何在android中自定义形状进度条,如苹果形状?

c++ - 在递归函数 C++ 中保持计数

c++ - myProgrammingLab "palindrome"挑战和递归

javascript递归计数器

recursion - Erlang:带有未优化尾调用的递归函数的stackoverflow?

python - 生成时将额外的分支添加到树中

java - `Thread.checkAccess()`是 `Thread.suspend()`的适当替代品吗?

java - 如何使用 AsyncHttpClient 对错误的 http 代码实现重试功能?