java定义贷款类Loan,如果贷款总额、利率或年数小于等于0,抛出异常。
时间: 2024-09-30 18:08:46 浏览: 29
在Java中,你可以定义一个名为`Loan`的类,包含贷款总额(principal)、年利率(interestRate)和贷款年限(years)等属性,并添加适当的构造函数和getter/setter方法。为了确保输入的有效性,我们需要在设置这些属性值时添加验证。当贷款总额、利率或年数小于等于0时,我们将抛出自定义的异常或者使用内置的`IllegalArgumentException`。这里是一个简单的示例:
```java
public class LoanException extends IllegalArgumentException {
public LoanException(String message) {
super(message);
}
}
public class Loan {
private double principal;
private double interestRate;
private int years;
// 构造函数进行参数校验
public Loan(double principal, double interestRate, int years) throws LoanException {
if (principal <= 0 || interestRate <= 0 || years <= 0) {
throw new LoanException("贷款金额、利率或年数不能小于等于0");
}
this.principal = principal;
this.interestRate = interestRate;
this.years = years;
}
// getter and setter methods
public double getPrincipal() {
return principal;
}
public void setPrincipal(double principal) {
if (principal <= 0) {
throw new IllegalArgumentException("贷款金额不能小于等于0");
}
this.principal = principal;
}
public double getInterestRate() {
return interestRate;
}
public void setInterestRate(double interestRate) {
if (interestRate <= 0) {
throw new IllegalArgumentException("利率不能小于等于0");
}
this.interestRate = interestRate;
}
public int getYears() {
return years;
}
public void setYears(int years) {
if (years <= 0) {
throw new IllegalArgumentException("年数不能小于等于0");
}
this.years = years;
}
}
// 使用示例
try {
Loan loan = new Loan(5000, 0.05, 5); // 正常创建贷款
} catch (LoanException e) {
System.out.println(e.getMessage());
}
```
在这个例子中,如果你尝试创建一个无效的贷款对象,比如负本金或零利率,将会抛出`LoanException`。
阅读全文