I have a program which reads a file and enforces a certain format in every line. If a line has a format error, it prints a line below it indicating which error it was.
For each line, From column 1 to 13 and 77 to 80, no formatting rules are enforced, so I don’t care about dots in these columns.
For the case of the dot character, every dot must not be preceded by white space, and it must be followed by white space.
I have a condition to check for this, and at a glance it seems right, but it’s still not catching errors in dot formatting.
public static boolean checkLineFormatErrors(String line){ int errorCount; if(line.contains(".")){ errorCount = 0; char[] charArr = line.toCharArray(); boolean problemWithDot = false; for(int i = 0; i < charArr.length;i++){ if(i < charArr.length - 1 && i > 12 && i < 76 && charArr[i] == '.' && (charArr[i-1] == ' ' || charArr[i+1] != ' ')){ problemWithDot = true; break; } } if(problemWithDot){ errorMessage = "One or more dots do not follow the line format for this file."; errorCount++; if(errorCount > 1){ System.out.println(errorMessage); } else{ System.out.println(line + errorMessage); } } } return problemWithDot }
All of my other methods for catching errors in format for other symbols work, it’s only the dot one that doesn’t.
For example
00012 ENVIRONMENT DIVISION . 00013 DATA DIVISION. 00014 WORKING-STORAGE SECTION. 00015 77 NUMERO1 PIC 9(2) VALUE ZEROS .
Line 12 and 15 should have an error message below them, because their final dot is preceded by a space.
(If you’re wondering “Hey isn’t that last bit of code Cobol?? Why are you not adding a cobol tag?” Yes those last lines are cobol! This is not a cobol issue because the program for checking the errors is made in Java only. Cobol is only a way to test the file to enforce its rules.)
Advertisement
Answer
By fixing your loop, it works, the main problem being with
i < charArr.length - 1
when the dot
is at the end
for(int i = 12; i < charArr.length && i < 76;i++) { if(charArr[i] == '.' && (charArr[i-1] == ' ' || charArr[Math.min(charArr.length -1, i+1)] != ' ')) { problemWithDot = true; break; } }
note
charArr[i+1] != ' '
is likely to cause problem so check that i + 1
does not exceed the array length.