Menu
CoddyTech

单词计数

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

我们将使用 HashMap 统计单词出现的频率。单词作为键,出现频率作为值。

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

挑战

简单

为程序添加单词计数功能。使用 HashMap 存储并统计单词出现的频率。打印每个不同单词的计数。

例如:

输入:

Coddy

预期输出:

Word counts:
coddy: 1

亲手试试

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

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

逻辑与流程中的所有课

自己练习: Java 在线编译器