异常练习(一)-银行取存钱

题目:

Account类: 银行账号
属性: balance 余额
方法: getBalance() 获取余额
方法: deposit() 存钱
方法: withdraw() 取钱
OverdraftException: 透支异常,继承Exception
属性: deficit 透支额

代码:

public class Account {
    public float balance;
    public float deficit;

    public Account() {
    }

    public Account(float balance) {
        this.balance = balance;
    }

    class OverdraftException extends Exception {
        public OverdraftException() {

        }
        public OverdraftException(String msg) {
            super(msg);
        }
    }

    public float getBalance() {
        return balance;
    }

    public void setBalance(float balance) {
        this.balance = balance;
    }

    public float deposit(float money) {
        balance = balance + money;
        return balance;
    }

    public float withdraw(float money) throws OverdraftException {
        if (balance < money) {
            deficit = money - balance;
            throw new OverdraftException("卡里已经没有这么多的钱了,透支额度为:" + deficit);
        }
        else {
            balance = balance - money;
            return balance;
        }
    }

    public static void main(String[] args) {
        Account account = new Account(5000);

        account.deposit(5000);

        try {
            account.withdraw(200000);
        } catch (OverdraftException e) {
            e.printStackTrace();
        }
        float balance = account.getBalance();
        System.out.println(balance);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值