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