修改withdraw 方法
練習目標-使用有返回值的方法:在本練習里,將修改withdraw方法以返回一個布爾值來指示交易是否成功。
?
任務
1.修改Account類
a.修改deposit 方法返回true(意味所有存款是成功的)。
b.修改withdraw方法來檢查提款數目是否大于余額。如果amt小于balance,則從余額中扣除提款數目并返回true,否則余額不變返回false。
2.在exercise2主目錄編譯并運行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類
package banking;
public class Account {
private double balance;
public Account(double i)
{
balance=i;
}
public double getBalance()
{
 return balance;
}
public boolean deposit(double i)
{
 balance+=i;
 System.out.print("Deposit "+i);
 return true;
}
public boolean withdraw(double i)
{
 if(balance>=i)
 {
 balance-=i;
 System.out.print("Withdraw "+i);
 return true;
 }
 else
 {
 System.out.print("余額不足");
 return false;
 }
}
}
//Testbanking類
package banking;
public class TestBanking {
public static void main(String[] args) {
 Account a=new Account(500.00);
 System.out.println("Creating an account with a "+a.getBalance()+"balance");
 a.withdraw(150.00);
 a.deposit(22.50);
 a.withdraw(47.62);
 System.out.println("The account has a balance of "+a.getBalance());
 Customer c=new Customer("Jane", "Smith");
 Account b=new Account(500.00);
 c.setAccount(b);
 a=c.getAccount();
 System.out.println("Creating her account with a "+a.getBalance()+"balance");
 System.out.println(":"+a.withdraw(150.00));
 System.out.println(":"+a.deposit(22.50));
 System.out.println(":"+a.withdraw(47.62));
 System.out.println("Customer ["+c.getFirstName()+","+c.getLastName()+"] has a balance of "+a.getBalance());
}
}
//運行
Creating an account with a 500.0balance
Withdraw 150.0Deposit 22.5Withdraw 47.62The account has a balance of 324.88
Creating the customer Jane Smith
Creating her account with a 500.0balance
Withdraw 150.0:true
Deposit 22.5:true
Withdraw 47.62:true
Customer [Jane,Smith] has a balance of 324.88
?
轉載于:https://www.cnblogs.com/smile-dream/p/5915467.html
總結
以上是生活随笔為你收集整理的修改withdraw 方法的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 【BZOJ-30391057】玉蟾宫棋盘
- 下一篇: 同是天涯沦落人下一句是什么啊?
