java - 使用 Java 在 for 循环之外返回值时遇到问题

标签 java for-loop

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

此外,您对 thefunctionjustSayit 函数调用也不正确 -

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

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

相关文章:

c++ - 变量嵌套 for 循环

java - Gradle : How to call implicit task provided by application plugin from other task

java - 如何创建包含混合 boolean 值和字符的数组列表?

php mysql for 循环

Java |通过 FOR 循环返回一个颠倒的数组

c - 如何在循环中增加IP地址? [C]

java - 生产中的 NoSuchMethodError 异常

java - 如何通过 Java 8 修复 Access DB 连接中的表?

java - 如何使用 RecyclerView 创建滚动返回顶部按钮

Python:在for循环中访问迭代器对象