📜  计算单利的Java程序(1)

📅  最后修改于: 2023-12-03 15:28:00.438000             🧑  作者: Mango

计算单利的Java程序

本程序是一个用Java编写的计算单利的工具。通过输入本金、利率和存款时间,即可快速得出存款利息和总金额。

代码说明

本程序由三个类组成:MainInterestCalculatorInputHelper

  • 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;
    }
}
使用说明
  1. 运行程序后,按提示输入本金(100元以上)、利率(小数,0.01 - 0.1之间)和存款时间(年)。
  2. 程序会计算出存款利息和总金额,并输出。
注意事项
  1. 本金必须是100元以上;
  2. 利率必须是小数,且在0.01 - 0.1之间;
  3. 存款时间必须是正整数年。