Menu
Coddy logo textTech

単語カウント

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腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン