Menu
Coddy logo textTech

高度な統計

CoddyのJavaジャーニー「ロジックとフロー」セクションの一部。レッスン 53/59。

ここでは、HashMap のメソッドを使用して最も一般的な単語と最も一般的でない単語を見つけ、割合を計算する高度な統計を追加します。

challenge icon

チャレンジ

簡単

プログラムを拡張して、次の内容を表示してください:

  1. 単語の総数
  2. 重複しない単語の数
  3. 各単語、その出現回数、および総数に対する割合を、単語ごとに1行で、アルファベット順に表示する(TreeMapはキーをソートされた状態で保持します。HashMapを使用する場合は、表示前にキーをソートしてください)

例:

入力:

Coddy!

期待される出力:

Total words: 1
Unique words: 1
Word statistics:
coddy: 1 (100.00%)
REQUIRED OUTPUT FORMAT: [Your translated content here]

自分で試してみよう

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オンラインコンパイラ