java编写一个程序,完成从某账户取款和存款的操作。 1)输人存取款金额时,如果非数值型,捕获异常并进行处理(系统异常)。 2)操作账户类时,如果取款数大于余额则作为异常处理(自定义异常)。具体的代码是什么
时间: 2024-10-19 19:15:20 浏览: 45
在Java中,我们可以创建一个简单的银行账户类`BankAccount`来实现存取款操作,并包含异常处理机制。这里是一个基本的示例:
```java
import java.util.Scanner;
import java.text.DecimalFormat; // 引入DecimalFormat用于格式化数字
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// 存款方法,处理输入验证
public void deposit(double amount) throws InsufficientBalanceException {
if (amount <= 0) { // 如果存款金额为负数或零,抛出异常
throw new IllegalArgumentException("Deposit amount must be positive.");
} else {
balance += amount;
}
System.out.println("Deposited " + DecimalFormat.getCurrencyInstance().format(amount) + ". New balance: $" + Double.parseDouble(DecimalFormat.getCurrencyInstance().format(balance)));
}
// 取款方法,处理余额不足异常
public void withdraw(double amount) throws InsufficientBalanceException {
try {
if (amount > balance) { // 检查余额是否足够
throw new InsufficientBalanceException("Insufficient balance for withdrawal.");
} else {
balance -= amount;
}
System.out.println("Withdrawn " + DecimalFormat.getCurrencyInstance().format(amount) + ". New balance: $" + Double.parseDouble(DecimalFormat.getCurrencyInstance().format(balance)));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BankAccount account = new BankAccount(1000); // 初始化一个账户
while (true) {
System.out.println("\nChoose an operation (deposit/withdraw):");
String input = scanner.nextLine();
switch (input.toLowerCase()) {
case "deposit":
System.out.print("Enter the deposit amount: ");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case "withdraw":
System.out.print("Enter the withdrawal amount: ");
double withdrawAmount = scanner.nextDouble();
try {
account.withdraw(withdrawAmount);
} catch (InsufficientBalanceException e) {
e.printStackTrace();
}
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
```
在这个程序中,用户可以选择存款或取款,输入金额后会根据操作进行相应的处理。如果输入的金额无效(如非数值或存款金额为负),`deposit`方法将抛出异常;如果取款金额超过当前余额,`withdraw`方法将抛出自定义的`InsufficientBalanceException`。
阅读全文