代码如下:
//计算贷款
package ClassDemo;
import javax.swing.JOptionPane;
public class ComputeLoan {
public static void main (String[] args) {
// 用户输入贷款总量
String loanString = JOptionPane.showInputDialog("请输入贷款总量:");
double loanAmount = Double.parseDouble(loanString);
// 用户输入年利率
String annualInterestStr = JOptionPane.showInputDialog("请输入贷款年利率(如7.00):");
double annualInterestRate = Double.parseDouble(annualInterestStr);
// 计算月利率
double monthlyInterestRate = annualInterestRate / 1200;
// 用户输入贷款年限
String numberOfYearsStr = JOptionPane.showInputDialog("请输入贷款年限:");
int numberOfYears = Integer.parseInt(numberOfYearsStr);
// 计算每月还款数额和总还款数额
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * 12 * numberOfYears;
// 将payment格式化为小数点后面的两位,采用向下取整的方式
monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
totalPayment = (int)(totalPayment * 100) / 100.0;
//输出结果,totalPayment 以及 monthlyPayment
String output = "月还款量:" + monthlyPayment + "\n总还款量:" + totalPayment;
JOptionPane.showMessageDialog(null, output);
}
}