Menu
Coddy logo textTech

Statistiche avanzate

Fa parte della sezione Logica e flusso del percorso Java di Coddy. Lezione 53 di 59.

Ora aggiungeremo statistiche avanzate usando i metodi di HashMap per trovare le parole più e meno comuni e calcolare le percentuali.

challenge icon

Sfida

Facile

Migliora il programma in modo che mostri:

  1. Il numero totale di parole
  2. Il numero di parole uniche
  3. Ogni parola con il relativo conteggio e la sua percentuale sul totale, una riga per parola, in ordine alfabetico (un TreeMap mantiene le chiavi ordinate; se usi un HashMap, ordina le chiavi prima di stamparle)

Per esempio:

Input:

Coddy!

Output previsto:

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

Provalo tu

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 iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore Java online