Counting Non-Empty Lines in a File
Assume the file sample.txt contains the following content, which consists of five lines including two empty lines.
Hello World
This is line 3
End of file
What is printed when the following code segment is executed?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class LineCounter {
public static void main(String[] args) throws IOException {
File textFile = new File("sample.txt");
Scanner reader = new Scanner(textFile);
int lineCount = 0;
while (reader.hasNextLine()) {
String line = reader.nextLine();
if (line.length() > 0) {
lineCount++;
}
}
reader.close();
System.out.println(lineCount);
}
}
A
5
B
4
C
3
D
2
Question Leaderboard
Not enough data yet to show leaderboard.
