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

题目:

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);
    }
}

 

你可能感兴趣的:(java编程,java)