Choosing how to earn college credit? CLEP vs AP guide
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Data Collections
Start Practice TestPractice Test
About Exam
medium Solved by 2 students

Counting Non-Empty Lines in a File

Mark
< Prev
Next >

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

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Instagram: @_apfive_|Privacy Policy|