编写程序计算贷款支付额

问题描述:程序要求用户输入月利率、还贷年数以及贷款金额,并要求显示月支付金额和总偿还金额。
给定的计算月支付额的公式如下:
月支付额= 11(1+)(12)

则编写此程序的步骤为:
1) 使用图形用户界面(调用JOptionPane类)提示用户输入年利率、年数和贷款总额;
2) 利用年利率获取月利率;
3) 使用给定的公式计算月支付额;
4) 计算总支付额,总支付额=月支付额12年数;
5) 显示月支付额和总支付额。

以下为完整代码:

import javax.swing.JOptionPane;
public class ComputeLoan {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Enter yearly interest rate
        String yearlyRateString = JOptionPane.showInputDialog(
         "Enter yearly interest rate,for example 8.25:");

        //convert string to double
        double yearlyRate = Double.parseDouble(yearlyRateString);

        //obtain monthly interest rate
        double monthlyRate = yearlyRate /1200;

        //Enter number of years
        String Years = JOptionPane.showInputDialog(
         "Enter number of years as an integer,\nfor example 5:");

        //convert string to int
        int numberOfYears = Integer.parseInt(Years);

        //Enter loan amount
        String loanString = JOptionPane.showInputDialog(
         "Enter loan number,for example 150000.95:");

        //convert string to double
        double loanAmount = Double.parseDouble(loanString);

        //Calculate payment
        double monthlyPayment = loanAmount * monthlyRate / (1 - 1 / Math.pow(1 + monthlyRate,numberOfYears * 12));

        double totalPayment = monthlyPayment * numberOfYears * 12;

        //Format to keep two digits after the decimal point
        monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
        totalPayment = (int)(totalPayment * 100) / 100.0;

        //Display results
        String output = "The monthly payment is " + monthlyPayment + 
                "\nThe total payment is " + totalPayment;
        JOptionPane.showMessageDialog(null, output);
    }

}

运行结果如下所示:
编写程序计算贷款支付额_第1张图片

编写程序计算贷款支付额_第2张图片

编写程序计算贷款支付额_第3张图片

编写程序计算贷款支付额_第4张图片

你可能感兴趣的:(Java)