Menu
Coddy logo textTech

Erweiterte Statistiken

Teil des Abschnitts Logik & Ablauf der Java-Journey von Coddy — Lektion 53 von 59.

Jetzt fügen wir fortgeschrittene Statistiken unter Verwendung von HashMap-Methoden hinzu, um die am häufigsten/seltensten vorkommenden Wörter zu finden und Prozentsätze zu berechnen.

challenge icon

Aufgabe

Einfach

Erweitere das Programm, um Folgendes anzuzeigen:

  1. Gesamtzahl der Wörter
  2. Anzahl der eindeutigen Wörter
  3. Häufigste(s) Wort(e)
  4. Seltenste(s) Wort(e)
  5. Prozentualer Anteil am Gesamten für jedes Wort

Zum Beispiel:

Eingabe:

Coddy!

Erwartete Ausgabe:

Total words: 1
Unique words: 1
Word statistics:
coddy: 1 (100.00%)

Probier es selbst

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 iconTeste dich selbst

Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.

Alle Lektionen in Logik & Ablauf