I have written a piece of code that counts the number of lines in a file (I wasn't able to find a built-in method that could acheive this in the IO classes). My code below:
try {
while(!line.equals("null")) {
line = bufferedReader.readLine();
a = a + 1;
System.out.println(a + " " + line);
}
} catch (NullPointerException N) {}
The problem I'm running into is that the count still increases while the variable 'line' evaluates to "null". I understand why this is the case; the while statement won't check the condition until after the entire code block has been run, in which case 'a' will have increased once again. Solutions I have considered:
1) Set 'a = -1', whereas I currently have 'a = 0' before this block of code 2) Use if statement to break the loop before the count variable is reached. This is how I would modify the code block:
try {
while(!line.equals("null")) {
line = bufferedReader.readLine();
if (line.equals("null")) {break;}
a = a + 1;
System.out.println(a + " " + line);
}
} catch (NullPointerException N) {}
My problem with the above? (1) seems too contrived while (2) seems redundant. I wanted to see if there's a better way to approach this - thanks for your suggestions.