4 changed files with 66 additions and 0 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -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()); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue