Java银行系统余额计算:处理错误输入和字母转换
以下为可能的Java代码实现:
public class BankSystem {
private int balance;
public BankSystem() {
balance = 0;
}
public int getBalance() {
return balance;
}
public void income(String in, String out) throws Exception {
int inValue = convertToInt(in);
int outValue = convertToInt(out);
if (inValue < 0 || outValue > 0) {
throw new Exception("Invalid input: in must be positive and out must be negative.");
}
int newBalance = balance + inValue + outValue;
if (newBalance < 0) {
throw new Exception("Invalid input: result balance cannot be negative.");
}
balance = newBalance;
}
private int convertToInt(String s) throws Exception {
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
s = s.replace(s.charAt(i), (char) s.charAt(i));
}
}
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
throw new Exception("Invalid input: cannot convert to integer.");
}
}
}
在income()方法中,先调用convertToInt()方法将输入的字符串转换成整数值。如果转换过程中出现异常,将抛出异常并打印出原因。如果输入的in和out不满足要求,也将抛出异常。
在convertToInt()方法中,先遍历字符串中的每个字符,如果不是数字,则将其替换成对应的ASCII码值。然后尝试将字符串转换成整数,如果出现NumberFormatException,则抛出异常并打印出原因。
原文地址: https://www.cveoy.top/t/topic/nWbz 著作权归作者所有。请勿转载和采集!