Menu
Coddy logo textTech

Word Counting

Part of the Logic & Flow section of Coddy's Java journey — lesson 52 of 59.

We'll use a HashMap to count word frequencies. The word will be the key, and its frequency will be the value.

HashMap<String, Integer> wordCount = new HashMap<>();
String word = "hello";
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
challenge icon

Challenge

Easy

Add word counting functionality to the program. Use a HashMap to store and count word frequencies. Print the count of each unique word.

For example:

Input:

Coddy

Expected Output:

Word counts:
coddy: 1

Try it yourself

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        
        String[] sentences = text.split("\\.");
        String[][] textArray = new String[sentences.length][];
        String[][] processedArray = new String[sentences.length][];
        
        for (int i = 0; i < sentences.length; i++) {
            textArray[i] = sentences[i].trim().split(" ");
            processedArray[i] = new String[textArray[i].length];
            
            for (int j = 0; j < textArray[i].length; j++) {
                if (!textArray[i][j].isEmpty()) {
                    processedArray[i][j] = textArray[i][j]
                        .replaceAll("[^a-zA-Z ]", "")
                        .toLowerCase();
                    System.out.println("Original[" + i + "," + j + "]: " + textArray[i][j]);
                    System.out.println("Processed[" + i + "," + j + "]: " + processedArray[i][j]);
                }
            }
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow