Java 银行系统账户余额计算:处理错误输入和异常情况
这是一个使用 Java 实现的简单银行系统,它能够处理存钱和支出操作,并能够识别和处理用户输入的错误信息,确保账户余额始终为非负值。
柜员通过调用 income(String in, String out) 方法向银行系统中录入存钱(即 in)和支出(即 out)的情况。现录入如下四条信息:
- ('200', '-100')
- ('3A32', '-342')
- ('9B5H', '-FC34')
- ('-300', '500')
系统根据录入信息计算账户里的最终余额。如 in='200', out='-100',则系统内当前余额为 '100'。
但是,由于柜员的误操作输入了一些字母。因此,若遇到字母,需自动将字母替换成对应的 ASCII 码值(如将 '3A32' 替换为 '36532'),再进行账户余额计算。
注意,存钱必须表示为正值,支出必须表示为负值,且每次 income() 调用完毕后,账户里的余额必须为非负值。如果不满足上述任意要求,则需要抛出异常,并打印出异常的原因,同时不利用该异常录入信息计算最终余额。
以下是可能的 Java 代码实现:
public class BankSystem {
private int balance;
public BankSystem() {
balance = 0;
}
public void income(String in, String out) throws Exception {
int inValue = parseAmount(in);
int outValue = parseAmount(out);
balance += inValue - outValue;
if (balance < 0) {
balance -= inValue - outValue;
throw new Exception("Invalid transaction: balance cannot be negative.");
}
}
private int parseAmount(String str) throws Exception {
int value;
try {
if (str.startsWith("-")) {
value = -Integer.parseInt(str.substring(1));
} else {
value = Integer.parseInt(str);
}
} catch (NumberFormatException e) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isDigit(c)) {
sb.append(c);
} else {
sb.append((int) c);
}
}
try {
value = Integer.parseInt(sb.toString());
} catch (NumberFormatException ex) {
throw new Exception("Invalid transaction amount: " + str);
}
}
if (value < 0 && str.startsWith("+")) {
throw new Exception("Invalid transaction amount: " + str);
}
return value;
}
public int getBalance() {
return balance;
}
}
使用示例:
```java
BankSystem bank = new BankSystem();
try {
bank.income("200", "-100");
bank.income("3A32", "-342");
bank.income("9B5H", "-FC34");
bank.income("-300", "500");
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Final balance: " + bank.getBalance());
原文地址: https://www.cveoy.top/t/topic/nWbU 著作权归作者所有。请勿转载和采集!