java实现从某账户取款和存款的操作 1)输人存取款金额时,如果非数值型,捕获异常并进行处理(系统异常)。2)操作账户类时,如果取款数大于金额则作为异常处理(自定义异常)。代码是什么
时间: 2024-10-21 18:16:02 浏览: 43
在Java中,我们可以创建一个`Account`类来代表银行账户,然后定义一个`withdraw`方法进行取款操作,一个`deposit`方法进行存款操作,并在其中包含异常处理。下面是一个简单的示例:
```java
import java.text.DecimalFormat;
import java.util.Scanner;
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class Account {
private double balance;
public Account(double initialBalance) {
this.balance = initialBalance;
}
// 存款方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. Current balance is " + formatMoney(balance));
} else {
throw new IllegalArgumentException("Invalid deposit amount");
}
}
// 取款方法
public void withdraw(double amount) throws InsufficientFundsException {
if (amount >= 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. Current balance is " + formatMoney(balance));
} else {
throw new InsufficientFundsException("Insufficient funds to withdraw the requested amount");
}
}
// 格式化金额显示
private String formatMoney(double amount) {
DecimalFormat df = new DecimalFormat("#.00");
return df.format(amount);
}
}
public class BankOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter your initial account balance: ");
double initialBalance = scanner.nextDouble();
Account myAccount = new Account(initialBalance);
while (true) {
System.out.println("\n1. Deposit\n2. Withdraw\n3. Quit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter deposit amount: ");
myAccount.deposit(scanner.nextDouble());
break;
case 2:
System.out.print("Enter withdrawal amount: ");
myAccount.withdraw(scanner.nextDouble());
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Invalid option.");
}
}
} catch (NumberFormatException e) {
System.out.println("Error: Please enter a valid number for the balance or transaction amounts.");
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
}
```
在这个例子中,用户输入初始余额、选择操作(存款或取款),然后输入相应的金额。如果输入的不是数字,会捕获`NumberFormatException`;如果取款金额超过账户余额,则抛出自定义的`InsufficientFundsException`。
阅读全文