一個簡單的java貸款程序
代碼如下:
//計算貸款
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);
}
}
一個簡單的java貸款程序