练习3:修改withdraw 方法

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

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/nicebaby/p/5907025.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值