实验题目
修改 withdraw 方法以返回一个布尔值,指示交易是否成功。
实验目的
使用有返回值的方法。
提示
- 修改 Account 类
- 修改 deposit 方法返回 true(意味所有存款是成功的)。
- 修改 withdraw 方法来检查提款数目是否大于余额。如果amt小于 balance, 则从余额中扣除提款数目并返回 true,否则余额不变返回 false。
- 在 exercise3 主目录编译并运行 TestBanking 程序,将看到下列输出:
CreatingthecustomerJaneSmith. Creatingheraccountwitha500.00balance. Withdraw150.00: trueDeposit22.50: trueWithdraw47.62: trueWithdraw400.00: falseCustomer [Smith, Jane] hasabalanceof324.88
代码
【Account.java】类
packagebanking; publicclassAccount { privatedoublebalance; //银行帐户的当前(或即时)余额//公有构造器 ,这个参数为 balance 属性赋值publicAccount(doubleinit_balance) { this.balance=init_balance; } //用于获取经常余额publicdoublegetBalance() { returnbalance; } /*** 向当前余额增加金额* @param amt 增加金额* @return 返回 true(意味所有存款是成功的)*/publicbooleandeposit(doubleamt){ balance+=amt; returntrue; } /*** 从当前余额中减去金额* @param amt 提款数目* @return 如果 amt小于 balance, 则从余额中扣除提款数目并返回 true,否则余额不变返回 false。*/publicbooleanwithdraw(doubleamt){ if (amt<balance){ balance-=amt; returntrue; }else{ returnfalse; } } }
【Customer.java】类
packagebanking; publicclassCustomer { privateStringfirstName; privateStringlastName; privateAccountaccount; publicCustomer(Stringf, Stringl) { this.firstName=f; this.lastName=l; } publicStringgetFirstName() { returnfirstName; } publicStringgetLastName() { returnlastName; } publicAccountgetAccount() { returnaccount; } publicvoidsetAccount(Accountacct) { this.account=acct; } }
【TestBanking.java】类
packagebanking;/** 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.*/importbanking.*; publicclassTestBanking { publicstaticvoidmain(String[] args) { Customercustomer; Accountaccount; // Create an account that can has a 500.00 balance.System.out.println("Creating the customer Jane Smith."); //codecustomer=newCustomer("Jane","Smith"); System.out.println("Creating her account with a 500.00 balance."); //codeaccount=newAccount(500.00); customer.setAccount(account); // Perform some account transactionsSystem.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 balanceSystem.out.println("Customer ["+customer.getLastName() +", "+customer.getFirstName() +"] has a balance of "+account.getBalance()); } }