Reputation: 23
Im trying to write a program that uses a recursive method to calculate how many months it will take to reach a goal of 10 million total invested if the same amount of money(inputted by the user) is invested with a 2 percent interest added each month. The problem is the method is returning counter too early so my "months" output is inaccurate. My guess is that my last else statement is wrong or my counter is placed incorrectly
Heres my code
import java.util.Scanner;
public class MoneyMakerRecursion {
public static int counter = 0;
public static void main(String[] args) {
//Variables declared
Scanner userInput = new Scanner(System.in);
double investment;
//User is prompted for input
System.out.println("Enter your monthly investment: ");
investment = userInput.nextInt();
//Method is called
Sum(investment);
//Results from recursive method output
System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
}
//recursive Method
public static double Sum(double investment) {
counter++;
double total = (investment * 0.02) + investment;
if(total >= 10000000) {return counter;}
else {return Sum(investment+total);}
}
}
Upvotes: 1
Views: 67
Reputation: 1462
Important point you missed is that your monthly investment is same throughout all months. Hence it should be static variable.
Second point you were adding investment to total which was local variable to that method. Which is not a actual investment for month. its a value passed to that function which changes for each month(Consider your code for this statement)
See below working code.
import java.util.Scanner;
public class MoneyMakerRecursion {
public static int counter = 0;
public static double investment = 0;
public static void main(String[] args) {
//Variables declared
Scanner userInput = new Scanner(System.in);
//User is prompted for input
System.out.println("Enter your monthly investment: ");
investment = userInput.nextInt();
//Method is called
Sum(investment);
//Results from recursive method output
System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
}
//recursive Method
public static double Sum(double totalInvestment) {
counter++;
double total = (totalInvestment* 0.02) + totalInvestment;
if(total >= 10000000) {return counter;}
else {return Sum(total+investment);}
}
}
Result
Enter your monthly investment:
100000
It should take 55 month(s) to reach your goal of $10,000,000
Here is snapshot: here interest is considered annually hence converting 0.02 monthly interest to per year interest it becomes 0.24
Upvotes: 1