Menu
CoddyTech

高级统计

本课属于 Coddy Java 学习旅程的“逻辑与流程”单元。第 53 课,共 59 课。

现在,我们将使用 HashMap 方法添加高级统计功能,以找出最常见和最不常见的单词,并计算百分比。

challenge icon

挑战

简单

增强程序,使其显示:

  1. 单词总数
  2. 不重复单词的数量
  3. 每个单词及其出现次数和占总数的百分比,每个单词占一行,并按字母顺序排列(TreeMap 会对键排序;如果使用 HashMap,请在打印前对键排序)

例如:

输入:

Coddy!

预期输出:

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

亲手试试

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 icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: Java 在线编译器