Menu
Coddy logo textTech

Advanced Statistics

Part of the Logic & Flow section of Coddy's Java journey. Lesson 53 of 59.

Now we'll add advanced statistics using HashMap methods to find the most/least common words and calculate percentages.

challenge icon

Challenge

Easy

Enhance the program to show:

  1. Total number of words
  2. Number of unique words
  3. Each word with its count and its percentage of the total, one line per word, in alphabetical order (a TreeMap keeps its keys sorted; if you use a HashMap, sort the keys before printing)

For example:

Input:

Coddy!

Expected Output:

Total words: 1
Unique words: 1
Word statistics:
coddy: 1 (100.00%)

Try it yourself

import java.util.*;

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][];
        HashMap<String, Integer> wordCount = new HashMap<>();
        
        for (int i = 0; i < sentences.length; i++) {
            textArray[i] = sentences[i].trim().split(" ");
            for (int j = 0; j < textArray[i].length; j++) {
                if (!textArray[i][j].isEmpty()) {
                    String word = textArray[i][j]
                        .replaceAll("[^a-zA-Z ]", "")
                        .toLowerCase();
                    wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
                }
            }
        }
        
        System.out.println("Word counts:");
        for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online Java compiler