我在for语句之外返回一个值时遇到了麻烦。在我的下面语法中,我必须在for循环之外声明 finalAmount 变量,因为如果我不这样做,它将无法工作。返回值为0,这是我不想要的。如何在Java中使用for循环语句之外的变量?
由于
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);
}
答案 0 :(得分:4)
我想你要添加所有这样的金额 -
for(int x = 1; x < year; x++){
finalAmount += amount * Math.pow(1.0 + rate, year); // +=
}
您对justSayit
的{{1}}函数调用也不正确 -
thefunction
答案 1 :(得分:2)
问题是当你对函数进行调用时,它的参数顺序错误:
double awesomeValue = thefunction(amount, year, rate);
该方法需要订单金额,费率,年度
答案 2 :(得分:0)
for循环中代码的问题在于它不依赖于循环变量x,所以很可能你忘记了某些东西,否则循环就没用了。