以下是一个实现你描述的银行账户类的示例代码:

// 自定义异常类:余额不足
class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

// 自定义异常类:取款数额为负数
class NegativeFundsException extends Exception {
    public NegativeFundsException(String message) {
        super(message);
    }
}

// 银行账户类
class Account {
    private double balance;

    // 构造方法初始化账户余额
    public Account(double balance) {
        this.balance = balance;
    }

    // 取款方法
    public void withDrawal(double amount) throws InsufficientFundsException, NegativeFundsException {
        if (amount < 0) {
            throw new NegativeFundsException("取款数额不能为负数");
        }
        if (amount > balance) {
            throw new InsufficientFundsException("余额不足");
        }
        balance -= amount;
    }

    // 获取账户余额
    public double getBalance() {
        return balance;
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        try {
            Account account = new Account(1000.0);
            System.out.println("账户余额:" + account.getBalance());
            
            // 正常取款
            account.withDrawal(500.0);
            System.out.println("账户余额:" + account.getBalance());
            
            // 余额不足
            account.withDrawal(800.0);
            System.out.println("账户余额:" + account.getBalance());
        } catch (InsufficientFundsException e) {
            System.out.println("错误:" + e.getMessage());
        } catch (NegativeFundsException e) {
            System.out.println("错误:" + e.getMessage());
        }
    }
}

这段代码定义了一个Account类,其中包含balance变量表示存款余额。构造方法Account(double balance)用于初始化账户余额。

withDrawal(double amount)方法用于进行取款操作。在取款过程中,首先会检查取款金额是否为负数,如果是则抛出NegativeFundsException异常;然后再检查取款金额是否大于账户余额,如果是则抛出InsufficientFundsException异常;如果都通过了检查,就从账户余额中减去取款金额。

main方法中进行了几个测试用例的演示。首先创建一个账户对象并打印初始余额,然后进行正常取款操作,再次打印余额。最后进行一次余额不足的取款操作,会抛出InsufficientFundsException异常并打印错误信息。

注意:在withDrawal方法中抛出自定义异常时,需要使用throws关键字声明可能抛出的异常类型。在main方法中使用try-catch语句捕获异常并进行相应处理

建立银行账户类Account类中有变量double balance表示存款Account类的构造方法能初始化账户余额Account类中有取款的方法withDrawaldouble dAmount当取款的数额大于存款时抛出自定义的InsufficientFundsException当取款数额为负数抛出自定义的NagativeFundsException。

原文地址: https://www.cveoy.top/t/topic/imUG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录