继续在循环中获得相同的答案但是由于我的回归而认为它

时间:2013-02-23 21:29:20

标签: java methods for-loop

我已经更新了我的代码,但是它继续将我初始化年份的数字放在表格底部,并在运行时打印出来。而且我还在试图弄清楚如何在打印输出部分中使用%.2d来创建2位小数。所以对此的反馈也会有所帮助。

import java.util.Scanner;

public class Investment {

public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years){

double futureInvestmentValue = 0.0;

for (years = 1; years <=30; years++){
    //calculate futureInvestmentValue
    futureInvestmentValue += (investmentAmount * (Math.pow(1 + monthlyInterestRate, years * 12)));
    System.out.print(years + "\t" + futureInvestmentValue + "\n");

}//end for
return futureInvestmentValue;
}//end futureInvestmentValue

public static void main(String[] args){

    Scanner input = new Scanner (System.in);

    //obtain Investment amount
    System.out.print("Enter Investment amount: ");
    double investmentAmount = input.nextDouble();

    //obtain monthly interest rate in percentage
    System.out.print("Enter annual interest rate in percentage: ");
    double annualInterestRate = input.nextDouble();

    //calculate annual interest rate
    double monthlyInterestRate = (annualInterestRate / 1200);

int years = 1;

System.out.println("Years\t" + "Future Value");

System.out.print(years + "\t" + futureInvestmentValue(investmentAmount, monthlyInterestRate, years) + "\n");

}//end main
}//

2 个答案:

答案 0 :(得分:0)

您永远不会修改计算此annualInterest

时使用的任何字词

double annualInterest = (1-1 / Math.pow(investmentAmount * (1 + monthlyInterestRate), years * 12));

答案 1 :(得分:0)

您将从扫描仪返回相同的值:

double investmentAmount = input.nextDouble();

您应该返回futureInvestmentValue。

而且,正如其他注释中所指出的那样,你是循环的,但是你没有改变,只是循环中变量的值,所以你可以避免循环或检查逻辑。