Menu
Coddy logo textTech

고급 통계

Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨. 59개 중 53번째.

이제 HashMap 메서드를 사용하여 가장 많이/적게 사용되는 단어를 찾고 백분율을 계산하는 고급 통계를 추가해 보겠습니다.

challenge icon

챌린지

쉬움

다음 항목을 표시하도록 프로그램을 개선하세요:

  1. 전체 단어 수
  2. 고유 단어 수
  3. 각 단어와 해당 단어의 개수 및 전체에서 차지하는 비율을 단어당 한 줄에 표시하며, 알파벳순으로 정렬합니다(TreeMap은 키를 정렬된 상태로 유지합니다. 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());
        }
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리와 흐름의 모든 레슨

직접 연습해 보세요: 온라인 Java 컴파일러