我在返回 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);
}
最佳答案
我认为您想要添加所有这样的金额 -
for(int x = 1; x < year; x++){
finalAmount += amount * Math.pow(1.0 + rate, year); // +=
}
此外,您对 thefunction
的 justSayit
函数调用也不正确 -
double awesomeValue = thefunction(amount, rate, year); /* not amount, year, rate */
关于java - 使用 Java 在 for 循环之外返回值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20928228/