고급 통계
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 53번째.
이제 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());
}
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.