首页 > 代码库 > 修改withdraw 方法

修改withdraw 方法

修改withdraw 方法

练习目标-使用有返回值的方法:在本练习里,将修改withdraw方法以返回一个布尔值来指示交易是否成功。

 技术分享

 

任务

 

1. 修改Account

  1. 修改deposit 方法返回true(意味所有存款是成功的)。
  2. 修改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

 

package banking;public class Account {    //成员属性    private double balance ;//余额    // 无参构造    public Account()     {            }    // 有参构造    public Account(double balance)     {        this.balance = balance;    }        // set  get     public double getBalance()    {        return balance;    }    public void setBalance(double balance)    {        this.balance = balance;    }            public boolean withdraw1( double amt )    {        if(amt>0&&amt<balance==true)        {            balance -= amt ;            System.out.print("Withdraw " + amt+" : ");            return true ;        }        else        {            System.out.print("Withdraw " + amt+" : ");            return false ;        }    }        public boolean deposit1( double amt )     {        if(amt<0)        {            System.out.print("Deposit " + amt+" : " );            return false ;        }        else        {            balance += amt ;            System.out.print("Deposit " + amt +" : ");            return true ;        }    }                    }
    Customer cr1 = new Customer( ) ;                cr1.setFirstName("Jane");        cr1.setLastName("Smith");        cr1.setBalance(500);        System.out.println("Creating the customer "+cr1.getFirstName() +" "+cr1.getLastName());        System.out.println("Creating her account  with  a " +cr1.getBalance()+" balance");        System.out.println(cr1.withdraw1(150) );        System.out.println(cr1.deposit1(22.5));        System.out.println(cr1.withdraw1(47.62));        System.out.println(cr1.withdraw1(400));        System.out.println("Customer "+cr1.getLastName()+" "+cr1.getFirstName()+                                            " has a balance of "+cr1.getBalance());        

 

技术分享

 

修改withdraw 方法