7-2 设计一个能处理异常的Loan类(JAVA)

7-2 设计一个能处理异常的Loan类:

定义一个贷款类Loan,其中有属性:
annualInterestRate: double,表示贷款的年利率(默认值:2.5)
numberOfYears: int,表示贷款的年数(默认值:1)
loanAmount: double,表示贷款额(默认值:100)
loanDate: java.util.Date,表示创建贷款的日期
定义方法:
(1)默认的无参构造方法
(2)带指定利率、年数和贷款额的构造方法
(3)所有属性的get/set方法
(4)返回这笔贷款的月支付额 getMonthlyPayment()
月支付额 = (贷款额度 * 月利率)/(1-(1/Math.pow(1+月利率,年数 * 12)))
(5)返回这笔贷款的总支付额 getTotalPayment()
总支付额度 = 月支付额度 * 年数 * 12

附上如下的测试类。

public class Main{
  public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      while (input.hasNext()) {
          double AIR = input.nextDouble();
          int NOY = input.nextInt();
          double LA = input.nextDouble();
          try {
              Loan m = new Loan(AIR, NOY, LA);
              System.out.printf("%.3f\n",m.getTotalPayment());
          } catch (Exception ex) {
              System.out.println(ex);
          }
      }
    
  }
}


输入格式:

输入有多组数据,一个实数表示年利率,一个整数表示年数,一个实数表示贷款总额。

输出格式:

若任意一项小于或等于零,抛出IllegalArgumentException异常及相应描述(Number of years must be positive或Annual interest rate must be positive或Loan amount must be positive);有多项不符合,以不符合最前项为准;

若均符合要求,按照格式输出总额。

输入样例:

在这里给出一组输入。例如:

1 1 1000
2.0 0 2000
0 0 0

输出样例:
在这里给出相应的输出。例如:

1005.425
java.lang.IllegalArgumentException: Number of years must be positive
java.lang.IllegalArgumentException: Annual interest rate must be positive

代码:

class Loan
{
    double annualInterestRate;
    int numberOfYears;
    double loanAmount;

    Loan() { annualInterestRate = 2.5; numberOfYears = 1; loanAmount = 100; }

    Loan(double annualInterestRate, int numberOfYears, double loanAmount)
    {
        if (annualInterestRate <= 0)
            throw new IllegalArgumentException("Annual interest rate must be positive");
        if (numberOfYears <= 0)
            throw new IllegalArgumentException("Number of years must be positive");
        if (loanAmount <= 0)
            throw new IllegalArgumentException("Loan amount must be positive");
        this.annualInterestRate = annualInterestRate;
        this.numberOfYears = numberOfYears;
        this.loanAmount = loanAmount;
    }

    public double getMonthlyPayment()
    {
        return (loanAmount * annualInterestRate / 1200) / (1 - 1 / Math.pow(1 + annualInterestRate / 1200, numberOfYears * 12));
    }

    public double getTotalPayment()
    {
        return getMonthlyPayment() * numberOfYears * 12;
    }
}
  • 8
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值