使用while循环来比较贷款支付与月利息 - 逻辑错误

时间:2011-12-06 02:33:39

标签: string if-statement while-loop logic

我目前正在开发一个while循环,它应该从用户贷款金额,年利息和每月付款中获取以下信息。它应该将每月利息与每月付款进行比较,如果第一个月的利息超过或等于指定的付款,则会打开一个对话框,要求提供更大的金额,直到每月付款高于利息为止。

在某些情况下似乎工作正常(如果我输入1000贷款,12%利息,以及任何低于121的付款,该程序要求更大的付款)。但是,如果我输入一个贷款金额和每月付款相近(500贷款金额400每月付款)我收到错误对话框,说明我没有输入足够大的金额。 咦!?

如果您可以看一下,这是我的代码。谢谢!

package program6;
import javax.swing.JOptionPane;

public class LoanAmount2 {

    public static void main(String[] args) {
        String loanAmountString = JOptionPane.showInputDialog(null, "Enter the amount for your loan.");
        double loanAmount = Double.parseDouble(loanAmountString);
        String annualInterestString = JOptionPane.showInputDialog(null, "Enter your annual interest rate.");
        double annualInterestRate = Double.parseDouble(annualInterestString);
        annualInterestRate = 1 + (annualInterestRate / 100);
        String monthlyPaymentString = JOptionPane.showInputDialog(null, "Enter the amount for your monthly payment.");
        double monthlyPayment = Double.parseDouble(monthlyPaymentString);
        double monthlyInterestRate = 1 + (annualInterestRate / 12);
        double monthlyInterest = loanAmount * monthlyInterestRate;
        while (monthlyInterest >= monthlyPayment) {
            monthlyPaymentString = JOptionPane.showInputDialog(null, "Your payment only covers the interest on your loan. Please enter a larger amount for your monthly payment.");
            monthlyPayment = Double.parseDouble(monthlyPaymentString);
            break;
        }

}

}

2 个答案:

答案 0 :(得分:2)

我刚刚运行此脚本并注意到了您的问题。这一行:

double monthlyInterestRate = 1 + (annualInterestRate / 12);

应阅读:

double monthlyInterestRate = annualInterestRate / 12;

如果您向其添加一个,则while循环将始终评估为true,因为您将全部贷款金额乘以1.xx

答案 1 :(得分:0)

我建议尝试将此问题分解为更小的部分。您可以在程序中多次重复此模式:

    String annualInterestString =
        JOptionPane.showInputDialog(null,
                    "Enter your annual interest rate.");
    double annualInterestRate =
        Double.parseDouble(annualInterestString);

如果您提供了类似以下的方法,我认为阅读代码会更容易:

double prompt_for_number(String prompt) {
    /* show dialog box */
    /* parse string into a Double */
    /* return number */
}

这可以让您重新编写代码:

loanAmount = prompt_for_number("Enter the amount for your loan.");
annualInterestRate = prompt_for_number("Enter your annual interest rate.");

这样可以更容易地看到所涉及的计算流程。 (并且会让你来到这里的实际错误更容易发现。)