SkyDC SkyDC - 1 month ago 6
Java Question

InputStream reading file and counting lines/words

I'm working on a project and I'm trying to count

1) The number of words.
2) The number of lines in a text file.

My problem is that I can't figure out how to detect when the file goes to the next line so I can increment lines correctly. Basically if next is not a space increment words and if next is a new line, increment lines. How would I do this? Thanks!

public static void readFile(Scanner f) {
int words = 0;
int lines = 0;
while (f.hasNext()) {
if (f.next().equals("\n")) {
lines++;
} else if (!(f.next().equals(" "))) {
words++;
}
}

System.out.println("Total number of words: " + words);
System.out.println("Total number of lines: " + lines);
}

Answer

Try this:

public static void readFile(Scanner f) {
    int words = 0;
    int lines = 0;
    while (f.hasNextLine()) {
        String line = f.nextLine();
        lines++;
        for (String token : line.split("\\s+")) {
            if (!token.isEmpty()) {
                words++;
            }
        }
    }
    System.out.println("Total number of words: " + words);
    System.out.println("Total number of lines: " + lines);
}
Comments