diff --git a/w7/BankWithdrawalTest$Account.class b/w7/BankWithdrawalTest$Account.class new file mode 100644 index 0000000..27d1272 Binary files /dev/null and b/w7/BankWithdrawalTest$Account.class differ diff --git a/w7/BankWithdrawalTest$InsufficientFundsException.class b/w7/BankWithdrawalTest$InsufficientFundsException.class new file mode 100644 index 0000000..0d160ba Binary files /dev/null and b/w7/BankWithdrawalTest$InsufficientFundsException.class differ diff --git a/w7/BankWithdrawalTest.class b/w7/BankWithdrawalTest.class new file mode 100644 index 0000000..979e835 Binary files /dev/null and b/w7/BankWithdrawalTest.class differ diff --git a/w7/BankWithdrawalTest.java b/w7/BankWithdrawalTest.java new file mode 100644 index 0000000..04fc778 --- /dev/null +++ b/w7/BankWithdrawalTest.java @@ -0,0 +1,66 @@ +public class BankWithdrawalTest { + + static class InsufficientFundsException extends Exception { + private double balance; + + public InsufficientFundsException(double balance) { + super("余额不足,当前余额:" + balance + " 元"); + this.balance = balance; + } + + public double getBalance() { + return balance; + } + } + + static class Account { + private double balance; + + public Account(double initialBalance) { + this.balance = initialBalance; + } + + public void withdraw(double amount) throws InsufficientFundsException { + if (amount <= 0) { + throw new IllegalArgumentException("取款金额必须大于0"); + } + if (amount > balance) { + throw new InsufficientFundsException(balance); + } + balance -= amount; + System.out.println("取款成功!取出:" + amount + " 元,剩余余额:" + balance + " 元"); + } + + public double getBalance() { + return balance; + } + } + + public static void main(String[] args) { + Account myAccount = new Account(1000.0); + + System.out.println("--- 测试1:正常取款 ---"); + try { + myAccount.withdraw(300); + } catch (InsufficientFundsException e) { + System.out.println("错误:" + e.getMessage()); + } + + System.out.println("\n--- 测试2:余额不足取款 ---"); + try { + myAccount.withdraw(800); + } catch (InsufficientFundsException e) { + System.out.println("取款失败:" + e.getMessage()); + System.out.println("提示:请检查取款金额,当前账户余额为 " + e.getBalance() + " 元"); + } + + System.out.println("\n--- 测试3:非法金额取款 ---"); + try { + myAccount.withdraw(-50); + } catch (IllegalArgumentException e) { + System.out.println("错误:" + e.getMessage()); + } catch (InsufficientFundsException e) { + System.out.println("取款失败:" + e.getMessage()); + } + } +}