高度な統計
CoddyのJavaジャーニー「ロジックとフロー」セクションの一部 — レッスン 53/59。
次に、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());
}
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。