请使用代码描述:
每一张借记卡(DebitCard)都有账号(accountNumber):和余额(money); 余额永远不能为负数
要求:当借记卡的余额为负数的时候需要抛出自定的异常
[Java] 纯文本查看 复制代码 //余额为负数的异常
public class UnlawfulMoneyException extends RuntimeException{
public UnlawfulMoneyException() {
// TODO Auto-generated constructor stub
}
public UnlawfulMoneyException(String message) {
super("余额不能为负数");
}
}
//借记卡类
public class DebitCard {
// 账号
private String accountNumber;
// 余额
private double money;
public DebitCard() {
// TODO Auto-generated constructor stub
}
public DebitCard(String accountNumber, double money) {
super();
if (money < 0)
throw new UnlawfulMoneyException("余额不能为负数");
this.accountNumber = accountNumber;
this.money = money;
}
// get/set
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
if (money < 0)
throw new UnlawfulMoneyException("余额不能为负数");
this.money = money;
}
}
/*请使用代码描述:
每一张借记卡(DebitCard)都有账号(accountNumber):和余额(money); 余额永远不能为负数
要求:当借记卡的余额为负数的时候需要抛出自定的异常*/
public class Test {
public static void main(String[] args) {
// DebitCard card = new DebitCard("1001", -1);
DebitCard card = new DebitCard("1001", 1);
System.out.println(card.getMoney());
}
} |