包含账号、余额属性,要求属性私有化,提供无参和有参构造,get/set方法(其中balance没有set方法) 包含public void withdraw(double money)取款方法,当取款金额为负数时,抛出Exception,异常信息为“越取你余额越多,想得美”,当取款金额超过余额时,抛出Exception,异常信息为“取款金额不足,不支持当前取款操作” 包含public void save(double money)存款方法,当取款金额为负数时,抛出Exception,异常信息为“越存余额越少,你愿意吗?”编写测试类,创建账号对象,并调用取款和存款方法,并传入非法参数,测试发生对应的异常
时间: 2023-11-01 07:07:36 浏览: 64
Java 反射创建get set方法及反射方法的调用
4星 · 用户满意度95%
好的,以下是代码实现:
```java
public class Account {
private String account;
private double balance;
// 无参构造
public Account() {
}
// 有参构造
public Account(String account, double balance) {
this.account = account;
this.balance = balance;
}
// Getter and Setter
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
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());
}
}
}
```
输出结果:
```
越取你余额越多,想得美
取款金额不足,不支持当前取款操作
越存余额越少,你愿意吗?
```
阅读全文