Menu
Coddy logo textTech

ספירת מילים

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-Java של Coddy. שיעור 52 מתוך 59.

נשתמש ב-HashMap כדי לספור את שכיחויות המילים. המילה תהיה המפתח, והשכיחות שלה תהיה הערך.

HashMap<String, Integer> wordCount = new HashMap<>();
String word = "hello";
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
challenge icon

אתגר

קל

הוסף לתוכנית פונקציונליות לספירת מילים. השתמש ב-HashMap כדי לאחסן ולספור את תדירויות המילים. הדפס את מספר המופעים של כל מילה ייחודית.

לדוגמה:

קלט:

Coddy

פלט צפוי:

Word counts:
coddy: 1

נסו בעצמכם

import java.util.Scanner;

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][];
        String[][] processedArray = new String[sentences.length][];
        
        for (int i = 0; i < sentences.length; i++) {
            textArray[i] = sentences[i].trim().split(" ");
            processedArray[i] = new String[textArray[i].length];
            
            for (int j = 0; j < textArray[i].length; j++) {
                if (!textArray[i][j].isEmpty()) {
                    processedArray[i][j] = textArray[i][j]
                        .replaceAll("[^a-zA-Z ]", "")
                        .toLowerCase();
                    System.out.println("Original[" + i + "," + j + "]: " + textArray[i][j]);
                    System.out.println("Processed[" + i + "," + j + "]: " + processedArray[i][j]);
                }
            }
        }
    }
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה לוגיקה וזרימת תוכנית

תרגלו בעצמכם: קומפיילר Java אונליין