Reputation: 75
I'm having trouble returning a value outside of a for statement. In my below syntax I have to declare the finalAmount variable outside of the for loop because if I don't it won't work. The return value is 0, which I don't want. How can I use the variable outside the for loop statement in Java?
Thanks
import java.util.Scanner;
public class CompundInterest2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double amount, rate, year;
System.out.println("What is the inital cost? Dude");
amount = input.nextDouble();
System.out.println("What is the interest rate?");
rate = input.nextDouble();
rate = rate/100;
System.out.println("How many years?");
year = input.nextDouble();
input.close();
justSayit(year, rate, amount);
}
private static double thefunction(double amount, double rate, double year){
double finalAmount = 0; // This is where I'm running into trouble. If I don't declare this variable the program won't work. But if I declare it, it works but returns 0.
for(int x = 1; x < year; x++){
finalAmount = amount * Math.pow(1.0 + rate, year);
}
return finalAmount;
}
public static void justSayit(double year, double rate, double amount){
double awesomeValue = thefunction(amount, year, rate);
System.out.println("For " + year + " years an initial " + amount +
" cost compounded at a rate of " + rate + " will grow to " + awesomeValue);
}
Upvotes: 0
Views: 87
Reputation: 36339
The trouble with the code in your for loop is that it doesn't depend on the loop variable x, so chances are that you forgot something or else the loop is useless.
Upvotes: 0
Reputation: 201527
I think you want to add all of the amounts like this -
for(int x = 1; x < year; x++){
finalAmount += amount * Math.pow(1.0 + rate, year); // +=
}
Also your justSayit
function call to thefunction
is incorrect -
double awesomeValue = thefunction(amount, rate, year); /* not amount, year, rate */
Upvotes: 4
Reputation: 330
The problem is that when you do the call to thefunction it has the parameters in the wrong order:
double awesomeValue = thefunction(amount, year, rate);
The method expects them in the order amount, rate, year
Upvotes: 2