1、声明银行账户类Account (1)包含账号、余额属性,要求属性私有化,提供无参和有参构造,get/set方法(其中balance没有 set方法) (2)包含public void withdraw(double money)取款方法,当取款金额为负数时,抛出Exception,异常信息为“越取你余额越多,想得美”,当取款金额超过余额时,抛出Exception,异常信息为“取款金额不足,不支持当前取款操作” (3)包含public void save(doublemoney)存款方法,当取款金额为负数时,抛出Exception,异常信息 为“越存余额越少,你愿意吗?" 2、编写测试类,创建账号对象,并调用取款和存款方法,并传入非法参数,测试发生对应的异常。
时间: 2023-12-11 14:05:20 浏览: 120
好的,根据您的要求,我来帮您完成这个问题。
Account类代码如下:
```java
public class Account {
private String accountNo;
private double balance;
public Account() {}
public Account(String accountNo, double balance) {
this.accountNo = accountNo;
this.balance = balance;
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public double getBalance() {
return balance;
}
public void withdraw(double money) throws Exception {
if (money < 0) {
throw new Exception("越取你余额越多,想得美");
}
if (money > balance) {
throw new Exception("取款金额不足,不支持当前取款操作");
}
balance -= money;
}
public void save(double money) throws Exception {
if (money < 0) {
throw new Exception("越存余额越少,你愿意吗?");
}
balance += money;
}
}
```
测试类代码如下:
```java
public class AccountTest {
public static void main(String[] args) {
Account account = new Account("123456", 1000.0);
try {
account.withdraw(-100.0);
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
account.withdraw(2000.0);
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
account.save(-100.0);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
```
当运行测试类时,输出结果为:
```
越取你余额越多,想得美
取款金额不足,不支持当前取款操作
越存余额越少,你愿意吗?
```
这说明我们的代码运行正常,能够正确地捕获并处理异常。
阅读全文