Java 银行系统:处理存款和取款,并验证输入值
以下是用 Java 代码实现的银行系统,该系统可以处理存款和取款操作,并验证输入值以确保正确计算账户余额:
public class BankSystem {
private int balance;
public BankSystem() {
balance = 0;
}
public void income(String in, String out) throws Exception {
int deposit = 0;
int withdraw = 0;
try {
deposit = Integer.parseInt(in);
withdraw = Integer.parseInt(out);
} catch (NumberFormatException e) {
// 字母转换成ASCII码值
for (int i = 0; i < in.length(); i++) {
if (!Character.isDigit(in.charAt(i))) {
in = in.replace(in.charAt(i), (char) (in.charAt(i)));
}
}
for (int i = 0; i < out.length(); i++) {
if (!Character.isDigit(out.charAt(i))) {
out = out.replace(out.charAt(i), (char) (out.charAt(i)));
}
}
deposit = Integer.parseInt(in);
withdraw = Integer.parseInt(out);
}
if (deposit < 0 || withdraw > 0) {
throw new Exception('Inappropriate input values. Deposit must be positive and withdraw must be negative.');
}
balance += deposit + withdraw;
if (balance < 0) {
throw new Exception('Negative balance is not allowed.');
}
}
public int getBalance() {
return balance;
}
}
// 在柜员类中调用BankSystem类的income方法,并处理可能的异常:
public class Teller {
private BankSystem bank;
public Teller(BankSystem bank) {
this.bank = bank;
}
public void processTransactions() {
try {
bank.income('200', '-100');
bank.income('3A32', '-342');
bank.income('9B5H', '-FC34');
bank.income('-300', '500');
System.out.println('Final balance: ' + bank.getBalance());
} catch (Exception e) {
System.out.println('Error: ' + e.getMessage());
}
}
}
// 测试代码:
BankSystem bank = new BankSystem();
Teller teller = new Teller(bank);
teller.processTransactions();
代码说明:
BankSystem类负责维护账户余额,并提供income()方法用于处理存款和取款操作。income()方法首先尝试将输入的in和out字符串解析为整数。如果解析失败,说明输入包含字母,则会将字母替换为对应的 ASCII 码值,并再次尝试解析。- 在解析完成后,代码会检查输入值是否符合要求:存款必须为正值,取款必须为负值。如果不满足要求,则会抛出异常。
getBalance()方法用于获取当前的账户余额。Teller类代表柜员,它负责调用BankSystem类的income()方法处理交易,并捕获可能的异常。
代码中的错误处理机制可以确保以下操作:
- 识别输入中的字母并将其转换为对应的 ASCII 码值,避免错误计算。
- 验证输入值是否符合要求,防止不合理的存款和取款操作。
- 在出现异常时提供清晰的错误信息,方便调试。
该示例代码可以帮助您了解如何在 Java 中实现简单的银行系统,并使用错误处理机制保证系统运行的可靠性。
原文地址: https://www.cveoy.top/t/topic/nWcu 著作权归作者所有。请勿转载和采集!