📅  最后修改于: 2023-12-03 15:28:00.438000             🧑  作者: Mango
本程序是一个用Java编写的计算单利的工具。通过输入本金、利率和存款时间,即可快速得出存款利息和总金额。
本程序由三个类组成:Main
、InterestCalculator
和InputHelper
。
Main
类负责调用InputHelper
类以获取用户输入,再调用InterestCalculator
类进行计算并输出结果。InterestCalculator
类负责计算存款利息和总金额。InputHelper
类负责获取用户输入并进行验证。public class Main {
public static void main(String[] args) {
InputHelper helper = new InputHelper();
double principal = helper.getPrincipal();
double rate = helper.getRate();
int years = helper.getYears();
InterestCalculator calculator = new InterestCalculator(principal, rate, years);
double interest = calculator.calculateInterest();
double total = calculator.calculateTotal();
System.out.println("利息是:" + interest);
System.out.println("总额是:" + total);
}
}
public class InterestCalculator {
private double principal;
private double rate;
private int years;
public InterestCalculator(double principal, double rate, int years) {
this.principal = principal;
this.rate = rate;
this.years = years;
}
public double calculateInterest() {
return principal * rate * years;
}
public double calculateTotal() {
return principal + calculateInterest();
}
}
import java.util.Scanner;
public class InputHelper {
public double getPrincipal() {
Scanner scanner = new Scanner(System.in);
double principal;
do {
System.out.print("请输入本金(100元以上):");
principal = scanner.nextDouble();
} while (principal < 100);
return principal;
}
public double getRate() {
Scanner scanner = new Scanner(System.in);
double rate;
do {
System.out.print("请输入利率(小数,0.01 - 0.1之间):");
rate = scanner.nextDouble();
} while (rate < 0.01 || rate > 0.1);
return rate;
}
public int getYears() {
Scanner scanner = new Scanner(System.in);
int years;
do {
System.out.print("请输入存款时间(年):");
years = scanner.nextInt();
} while (years <= 0);
return years;
}
}