代码错误 - Java储蓄帐户

时间:2014-11-25 22:07:12

标签: java

有一个输出混乱,它将我的所有余额转换为0.000000

这是我的代码:

package savingsaccountclass;

import java.util.Scanner;

public class SavingsAccountClass 
{
    public static void main(String[] args) 
    {
        double annualInterestRate;
        double savingsBalance;
        double[] postInterestBalance = new double[100];
        int counter = 0;

        Scanner entry = new Scanner(System.in);

        System.out.println("Enter the current annual interest rate");
        annualInterestRate = entry.nextDouble();

        System.out.println("Enter the current balance.");
        savingsBalance = entry.nextDouble();

        while (counter < 12)
        {
            postInterestBalance[counter] = calculateMonthlyInterest(savingsBalance, annualInterestRate);
            System.out.printf("After Month %d. %f\n", counter + 1, postInterestBalance[counter]);
            counter++;
        }
    }

    public static double calculateMonthlyInterest(double balance, double interest)
    {
        double[] array = new double[100];
        int c = 0;
        double done = (balance * (interest/12));
        while (c < 12)
        {
            array[c] = (((c + 1) * done) + balance);
            c++;
        }
        return array[c];
    }
}

这是我的输出:

run:
Enter the current annual interest rate
1
Enter the current balance.
100
After Month 1. 0.000000
After Month 2. 0.000000
After Month 3. 0.000000
After Month 4. 0.000000
After Month 5. 0.000000
After Month 6. 0.000000
After Month 7. 0.000000
After Month 8. 0.000000
After Month 9. 0.000000
After Month 10. 0.000000
After Month 11. 0.000000
After Month 12. 0.000000
BUILD SUCCESSFUL (total time: 1 second)

如果有人能让我知道为什么一切都会变成0,我真的很感激。 谢谢:))

1 个答案:

答案 0 :(得分:3)

您正在填写数组中的第一个12余额,但是您将返回array[12],这是从未分配的,因此它是0

返回array[c - 1]以返回数组的最后一个填充元素。

此外,您的1利率被解释为100%,即100/12,或每月增加8 1/3%。将利率除以100,将百分比转换为所需的小数。

此外,您目前还没有计算复利。您当前正在计算初始余额100上每个“月”的当前利息。相反,您需要根据上个月的余额计算月利息,而不是初始余额,使用array[c - 1]来访问上个月的余额。