19.编写一个程序,模拟银行转账过程,处理可能的余额不足异常。
下面是一个简单的Java程序,用于模拟银行转账过程,并处理可能的余额不足异常。
首先,我们定义一个BankAccount
类,该类包含账户的基本信息(如账户名和余额)以及一个transfer
方法用于转账。如果转账导致余额不足,transfer
方法将抛出InsufficientBalanceException
异常。
然后,我们定义一个InsufficientBalanceException
类,该类继承自Exception
类,用于表示余额不足的异常情况。
最后,我们在Main
类中创建两个BankAccount
对象,并模拟转账过程。
java复制代码
|---|----------------------------------------------------------------------------------------------------|
| | // BankAccount.java
|
| | public class BankAccount {
|
| | private String name;
|
| | private double balance;
|
| | |
| | public BankAccount(String name, double balance) {
|
| | this.name = name;
|
| | this.balance = balance;
|
| | }
|
| | |
| | public void deposit(double amount) {
|
| | this.balance += amount;
|
| | }
|
| | |
| | public void withdraw(double amount) throws InsufficientBalanceException {
|
| | if (amount > balance) {
|
| | throw new InsufficientBalanceException("Insufficient balance in account " + name);
|
| | }
|
| | this.balance -= amount;
|
| | }
|
| | |
| | public void transfer(BankAccount receiver, double amount) throws InsufficientBalanceException {
|
| | withdraw(amount);
|
| | receiver.deposit(amount);
|
| | }
|
| | |
| | public String getName() {
|
| | return name;
|
| | }
|
| | |
| | public double getBalance() {
|
| | return balance;
|
| | }
|
| | }
|
| | |
| | // InsufficientBalanceException.java
|
| | public class InsufficientBalanceException extends Exception {
|
| | public InsufficientBalanceException(String message) {
|
| | super(message);
|
| | }
|
| | }
|
| | |
| | // Main.java
|
| | public class Main {
|
| | public static void main(String[] args) {
|
| | BankAccount account1 = new BankAccount("Alice", 1000);
|
| | BankAccount account2 = new BankAccount("Bob", 500);
|
| | |
| | try {
|
| | account1.transfer(account2, 600); // Alice transfers 600 to Bob
|
| | System.out.println("Transfer successful.");
|
| | System.out.println("Alice's balance: " + account1.getBalance());
|
| | System.out.println("Bob's balance: " + account2.getBalance());
|
| | } catch (InsufficientBalanceException e) {
|
| | System.out.println("Transfer failed: " + e.getMessage());
|
| | }
|
| | }
|
| | }
|
在上面的示例中,我们创建了两个BankAccount
对象:account1
(属于Alice,余额为1000)和account2
(属于Bob,余额为500)。然后,我们尝试从account1
向account2
转账600元。由于account1
的余额足够,转账将成功执行,并打印出转账后的余额。如果我们尝试转账的金额超过账户的余额,transfer
方法将抛出InsufficientBalanceException
异常,并在catch
块中捕获该异常,打印出相应的错误消息