在Java中复合兴趣程序

时间:2013-10-03 03:40:54

标签: java while-loop do-while

我正在尝试用最后的do while循环编写这个复合兴趣程序,我无法弄清楚如何打印出最终的金额。

这是我到目前为止的代码:

public static void main(String[] args) {
    double amount;
    double rate;
    double year;

    System.out.println("This program, with user input, computes interest.\n" +
    "It allows for multiple computations.\n" +
    "User will input initial cost, interest rate and number of years.");

    Scanner keyboard = new Scanner(System.in);

    System.out.println("What is the initial cost?");
    amount = keyboard.nextDouble();

    System.out.println("What is the interest rate?");
    rate = keyboard.nextDouble();
    rate = rate/100;

    System.out.println("How many years?");
    year = keyboard.nextInt();


    for (int x = 1; x < year; x++){
        amount = amount * Math.pow(1.0 + rate, year);
                }
    System.out.println("For " + year + " years an initial " + amount + " cost compounded at a rate of " + rate + " will grow to " + amount);


    String go = "n";
    do{
        System.out.println("Continue Y/N");
        go = keyboard.nextLine();
    }while (go.equals("Y") || go.equals("y"));
}

}

1 个答案:

答案 0 :(得分:1)

问题是,amount = amount * Math.pow(1.0 + rate, year);。您将使用计算的金额覆盖原始金额。您需要一个单独的值来保持计算值,同时仍保持原始值。

所以:

double finalAmount = amount * Math.pow(1.0 + rate, year);

然后在你的输出中:

System.out.println("For " + year + " years an initial " + amount + 
    " cost compounded at a rate of " + rate + " will grow to " + finalAmount);

编辑:或者,你可以保存一行,一个变量,然后直接进行内联计算:

System.out.println("For " + year + " years an initial " + amount + 
    " cost compounded at a rate of " + rate + " will grow to " + 
    (amount * Math.pow(1.0 + rate, year)));