[JAVA] 5. Java重构之后的贷款计算器
Posted modai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[JAVA] 5. Java重构之后的贷款计算器相关的知识,希望对你有一定的参考价值。
MorgageCalculator
package com.modai;
import java.util.Scanner;
public class MorgageCalculator {
public final static byte MONTH = 12;
public final static byte PERCENT = 100;
private float principle;
private float monthlyInterest;
private short numberOfMonth;
public MorgageCalculator(float principle, float interest, byte years) {
this.principle = principle;
monthlyInterest = interest / MONTH / PERCENT;
numberOfMonth = (short) (MONTH * years);
}
public static double getNumber(String prompt, double min, double max, Scanner scanner) {
double value = 0;
while (true) {
System.out.print(prompt + ‘:‘);
value = scanner.nextFloat();
if (value > min && value < max)
break;
System.out.println("数据应当在" + min + " " + max + "之间。");
}
return value;
}
public double getBalance(short numberOfPaymentsMade) {
double balance = principle
* (Math.pow(1 + monthlyInterest, numberOfMonth) - Math.pow(1 + monthlyInterest, numberOfPaymentsMade))
/ (Math.pow(1 + monthlyInterest, numberOfMonth) - 1);
return balance;
}
public double getMortgage() {
double mortgage = principle
* monthlyInterest * Math.pow(1 + monthlyInterest, numberOfMonth)
/ (Math.pow(1 + monthlyInterest, numberOfMonth) - 1);
return mortgage;
}
public double[] getBalanceMonthly(){
var balanceArr = new double[numberOfMonth];
for (short month = 1; month <= numberOfMonth; month++) {
balanceArr[month-1]= getBalance(month);
}
return balanceArr;
}
}
Console.java
package com.modai;
import java.text.NumberFormat;
public class Console {
private static MorgageCalculator calcuator;
private static NumberFormat currency;
public Console(MorgageCalculator calcuator) {
this.calcuator = calcuator;
currency = NumberFormat.getCurrencyInstance();
}
public static void printBalanceInfo(byte years) {
System.out.println(" 结 余 ");
System.out.println("-------");
for (double balance: calcuator.getBalanceMonthly())
System.out.println("月结余: " + currency.format(balance));
}
public static void printMorgageInfo() {
double mortgage = calcuator.getMortgage();
System.out.println();
System.out.println(" 贷 款 ");
System.out.println("-------");
System.out.println("月供为:" + currency.format(mortgage));
System.out.println();
}
}
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
float principle = (float) MorgageCalculator.getNumber("请输入本金", 1000, 1_000_000, scanner);
float interest = (float) MorgageCalculator.getNumber("请输入年利率", 1, 2, scanner);
byte years = (byte) MorgageCalculator.getNumber("请输入贷款年限", 5, 20, scanner);
var morgageCalculator = new MorgageCalculator(principle, interest, years);
var console = new Console(morgageCalculator);
console.printMorgageInfo();
console.printBalanceInfo();
}
}
以上是关于[JAVA] 5. Java重构之后的贷款计算器的主要内容,如果未能解决你的问题,请参考以下文章