使用Java在for循环之外返回值时遇到问题
返回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);
}
# 1 楼答案
我想你应该把所有的金额都加起来
另外,对
thefunction
的justSayit
函数调用不正确-# 2 楼答案
for循环中的代码的问题在于它不依赖于循环变量x,所以很可能是您忘记了什么,或者循环没有用
# 3 楼答案
问题是,当您调用函数时,它的参数顺序错误:
该方法以订单金额、费率、年份为准