修改 withdraw 方法以返回一个布尔值,指示交易是否成功。 实验目的: 使用有返回值的方法。 提 示: 1. 修改 Account 类 a. 修改 deposit 方法返回 true(意味所有存款是成功的)。 b. 修改 withdraw 方法来检查提款数目是否大于余额。如果amt小于 balance, 则从余额中扣除提款数目并返回 true,否则余额不变返回 false。 2. 在 exercise3 主目录编译并运行 TestBanking 程序,将看到下列输出; Creating the customer Jane Smith. Creating her account with a 500.00 balance. Withdraw 150.00: true Deposit 22.50: true Withdraw 47.62: true Withdraw 400.00: false Customer [Smith, Jane] has a balance of 324.88
时间: 2024-02-26 11:58:52 浏览: 16
好的,根据你的要求,下面是修改后的Account类的代码:
```
public class Account {
private double balance;
public Account(double initBalance) {
balance = initBalance;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance += amt;
return true;
}
public boolean withdraw(double amt) {
if (amt <= balance) {
balance -= amt;
return true;
} else {
return false;
}
}
}
```
在withdraw方法中,我们首先检查提款数目是否小于等于账户余额。如果是,我们从余额中扣除提款数目并返回true,表示交易成功。否则,我们不做任何操作并返回false,表示交易失败。
在TestBanking类中,我们可以测试修改后的Account类,得到以下输出:
```
Creating the customer Jane Smith.
Creating her account with a 500.00 balance.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: false
Customer [Smith, Jane] has a balance of 324.88
```
可以看到,前三次交易都成功了,最后一次交易因为提款数目大于余额而失败了。同时,我们还能够通过返回值判断每次交易是否成功。