[英]Having trouble returning a value outside of a for loop with Java
我在返回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); // +=
}
此外,您的justSayit
函數調用thefunction
是不正確-
double awesomeValue = thefunction(amount, rate, year); /* not amount, year, rate */
問題是,當您調用該函數時,它具有錯誤順序的參數:
double awesomeValue = thefunction(amount, year, rate);
該方法在訂單金額,費率,年份中期望它們
for循環中代碼的麻煩在於它不依賴於循環變量x,因此很可能您忘記了某些內容,否則循環將無用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.