实验题目
修改 withdraw 方法以返回一个布尔值,指示交易是否成功。
实验目的
使用有返回值的方法。
提示
-
修改 Account 类
- 修改 deposit 方法返回 true(意味所有存款是成功的)。
- 修改 withdraw 方法来检查提款数目是否大于余额。如果amt小于 balance, 则从余额中扣除提款数目并返回 true,否则余额不变返回 false。
-
在 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
代码
【Account.java】类
package banking;
public class Account {
private double balance; //银行帐户的当前(或即时)余额
//公有构造器 ,这个参数为 balance 属性赋值
public Account(double init_balance) {
this.balance = init_balance;
}
//用于获取经常余额
public double getBalance() {
return balance;
}
/**
* 向当前余额增加金额
* @param amt 增加金额
* @return 返回 true(意味所有存款是成功的)
*/
public boolean deposit(double amt){
balance+=amt;
return true;
}
/**
* 从当前余额中减去金额
* @param amt 提款数目
* @return 如果 amt小于 balance, 则从余额中扣除提款数目并返回 true,否则余额不变返回 false。
*/
public boolean withdraw(double amt){
if (amt < balance){
balance-=amt;
return true;
}else{
return false;
}
}
}
【Customer.java】类
package banking;
public class Customer {
private String firstName;
private String lastName;
private Account account;
public Customer(String f, String l) {
this.firstName = f;
this.lastName = l;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Account getAccount() {
return account;
}
public void setAccount(Account acct) {
this.account = acct;
}
}
【TestBanking.java】类
package banking;/*
* This class creates the program to test the banking classes.
* It creates a new Bank, sets the Customer (with an initial balance),
* and performs a series of transactions with the Account object.
*/
import banking.*;
public class TestBanking {
public static void main(String[] args) {
Customer customer;
Account account;
// Create an account that can has a 500.00 balance.
System.out.println("Creating the customer Jane Smith.");
//code
customer = new Customer("Jane","Smith");
System.out.println("Creating her account with a 500.00 balance.");
//code
account = new Account(500.00);
customer.setAccount(account);
// Perform some account transactions
System.out.println("Withdraw 150.00: " + account.withdraw(150.00));
System.out.println("Deposit 22.50: " + account.deposit(22.50));
System.out.println("Withdraw 47.62: " + account.withdraw(47.62));
System.out.println("Withdraw 400.00: " + account.withdraw(400.00));
// Print out the final account balance
System.out.println("Customer [" + customer.getLastName()
+ ", " + customer.getFirstName()
+ "] has a balance of " + account.getBalance());
}
}