I have a multi-line text input file: If the String “Log Number:” is present, it is immediately followed by a log number. If the String “Log Number:” is not present, there is no log number in that record. There is ALWAYS the String “Log Date:”. It follows “Log Number:” if present and appears at that position in the file if it does not.
My inputLine comes out of a BufferedReader that’s reading my file line-by-line.
...
if((inputLine.indexOf("Log Number:"))>-1) {
logNumRecStart = inputLine.indexOf("Log Number:")+12;}
else
logNumRecStart = 0;
logNumRecEnd = inputLine.indexOf("Log Date:");
...
logNumber = inputLine.substring(logNumRecStart,logNumRecEnd);
...
and when I output the Start and End indeces, here’s a sample of what I get.
49>>> -0 to 357
50>>> -0 to 361
51>>> -0 to 384
52>>> -371 to 390
53>>> -315 to 334
54>>> -325 to 352
Records 49-51 are cases where “Log Number:” does not appear in the input line, and as expected, logNumRecStart is set to 0. Records 52 – 54 do include “Log Number:”, but the index is being set to a negative number, resulting in my substring getting an out-of-bounds exception. Visually inspecting the file demonstrated the presence (or absence) of the test values in the appropriate lines. My logNumRecEnd value is correct in ALL cases.
By counting characters in the source file for inputLine, I’ve verified that if the negative value of logNumRecStart were POSITIVE, it’d be the correct number.
I’m not using lastIndexOf so I have no idea why I’m getting the negative values. Can anyone see something I’m missing or soemthing I need to check that I’ve not mentioned?
This is all correct and is giving you correct values, so your error must be in the … that you left out somewhere.