My program reads lines from a plain text file w/ lines formatted: <integer>;<integer>%n, where ; is the delimiter. It compares the two parsed integers against 2 other known values and increments tallyArray[i] if they match.
I currently use:
try {
scan = new Scanner(new BufferedReader(new FileReader("LogFileToBeRead.txt")));
for (int i = 0; i < tallyArraySize; i++) {
explodedLogLine = scan.nextLine().split(";");
if (IntReferenceVal1 == Integer.parseInt(explodedLogLine[0]) && IntReferenceVal2 == Integer.parseInt(explodedLogLine[1])) {
tallyArray[i]++;
}
}
} finally {
if (scan != null) { scan.close(); }
}
I was wondering if there were any serious faults with this method. It does not need to be production-quality.
Also, is there a standard way of parsing a string like this?
EDIT: We can assume the text file is perfectly formatted. But I see the importance for accounting for possible exceptions.
You are not handling
NumberFormatExceptionsthrown by theInteger.parseInt()method calls. If there’s one bad line, execution exits your for loop.You aren’t vetting the integrity of the file you are reading from. If there isn’t a
;character or if the Strings aren’t actually numbers, execution simply exits the code block you posted.If you can assume the file is perfectly formatted, and you’re set on using a Scanner, you can add
;as a delimiter to the Scanner:And simply call
Scanner.nextInt()twice for each line.