我正在为一个项目编写一个异常类,并且遇到了一个问题。该类要求一个包含银行帐户的文件名,读取该文件,并检查它们是否符合某些条件。如果它们不满足这些条件之一,则会引发 BankAccountException 类型的错误,这是一个自定义错误类,只是extends
该类Exception
并被重命名。我遇到的问题是,一旦我输入文件名,程序会立即询问另一个文件的名称。我已经坐了一段时间,无法弄清楚,任何帮助将不胜感激。
import java.util.*;
import java.io.*;
public class BankAccountProcessor{
public static void main(String[] args){
boolean runProgram = true;
Scanner input = new Scanner(System.in);
String filename;
while (runProgram = true){
try{
System.out.println("Please enter the name of the file you want to parse.");
filename = input.next();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
String accountLine = inputFile.nextLine();
if (BankAccountProcessor.isValid(accountLine) == true){
System.out.println("Line " + accountLine + " has been processed.");
}
runProgram = false;
}
}
catch(FileNotFoundException e){
System.out.println("That file does not exist");
}
catch(BankAccountException e){
}
}
}
private static boolean isValid(String accountLine) throws BankAccountException{
StringTokenizer stringToken = new StringTokenizer(accountLine, ";");
String tokenOne = stringToken.nextToken();
String tokenTwo = stringToken.nextToken();
if (stringToken.countTokens() != 2){
throw new BankAccountException("Invalid Bank Account Info");
}
else if (tokenOne.length() != 10){
throw new BankAccountException("Invalid Bank Account Info: Account Number is not 10 digits.");
}
else if (tokenTwo.length() < 3){
throw new BankAccountException("Invalid Bank Account Info: Name must be more than 3 letters.");
}
else if (BankAccountProcessor.hasLetter(tokenOne) == true){
throw new BankAccountException("Invalid Bank Account Info: Account Number must be all digits.");
}
else if (BankAccountProcessor.hasDigit(tokenTwo) == true){
throw new BankAccountException("Invalid Bank Account Info: Account Name cannot have digits.");
}
return true;
}
private static boolean hasDigit(String str){
for (char c : str.toCharArray()){
if (Character.isDigit(c)){
return true;
}
}
return false;
}
private static boolean hasLetter(String str){
for (char c : str.toCharArray()){
if (Character.isLetter(c)){
return true;
}
}
return false;
}
}