1

わかりました、私は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);
    }
  }
}
  • ザック
4

5 に答える 5

0

Month()はコード内で 1 回だけ呼び出されるため、 を認識しcounter == 0、それをインクリメントして を与えcounter == 1ます。これは印刷される値です。

だから、あなたcounter++は間違った場所にいます。Sum()メソッドの上部にある必要があります。これは再帰的に呼び出されるメソッドであるため、ここでカウンターがインクリメントされます。

getMonth()が呼び出されると、適切な値が設定されます。

于 2013-04-25T23:41:44.180 に答える