Skip to content
Advertisement

how to count the number of words in each line in Java?

My task is to count the number of words on each line of a text file, separated by space. The text file has 5 lines. I am very new to Java. I have so far this code with the B1TextLoader class and several methods.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.ConcurrentHashMap;

public class B1TextLoader {

    ConcurrentHashMap<String, String> documents = new ConcurrentHashMap<String, String>();

    public static void main(String[] args) {

        B1TextLoader loader = new B1TextLoader();
        loader.LoadTextFile("2-3-1BasicTextFile.txt");  
    }

    public void LoadTextFile(String filePath) {

        try {
            System.out.println("Loading file...");
            File f = new File(filePath);
            BufferedReader br = new BufferedReader(new FileReader(f));

            String line = br.readLine();
            Integer counter = 0;
            while (line != null)

            {
                if (line.trim().length() > 0) {
                    documents.put("doc" + counter, line);
                    ;
                    counter++;

                }
                line = br.readLine();
                
            }
            br.close();
        } catch (Exception e) {
            System.out.println("File Load Failed");
        }
        
        System.out.println("Load Complete. Lines loaded: " + documents.size());

    }

    public void CountWordsInDocuments(ConcurrentHashMap<String, String> documents)

    {
        CountWordsInDocuments(documents);

    }
    
    public void CountWordsInDocument(String key, String value)

    {
        String[] words = value.split(" ");
        System.out.println(key + " has " + words.length + " words!");
        documents.forEach(this::CountWordsInDocument);
    }
}


My output is:

Loading file...
Load Complete. Lines loaded: 5

however, I want it to print something like

Loading file...
Load Complete. Lines loaded: 5
doc0 has 6 words!
doc1 has 8 words!
doc2 has 4 words!
doc3 has 4 words!
doc4 has 6 words!

How can I achieve this?

my text file, 2-3-1BasicTextFile.txt, looks like this:

this is a simple text file
you should find that it has five lines
each of varying lengths
and no dirty data
which might make it go wrong

Advertisement

Answer

Try This

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * B1TextLoader
 */
public class B1TextLoader {

    public static void main(String[] args) {
        B1TextLoader loader = new B1TextLoader();
        loader.LoadTextFile("./text.txt");
    }

    public void LoadTextFile(String filePath) {
        System.out.println("loading file ...");
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            Object[] lines = br.lines().toArray();
            System.out.println("Load Complete. Lines loaded: " + lines.length);
            for (int i = 0; i < lines.length; i++) {
                System.out.println("doc" + i + " has " + lines[i].toString().split(" ").length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement