我在返回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); // +=
}


另外,您对justSayitthefunction函数调用不正确-

double awesomeValue = thefunction(amount, rate, year); /* not amount, year, rate */

关于java - 用Java在for循环之外返回值时遇到麻烦,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20928228/

10-10 13:58