Java, a word occour counter

avatar

A small application written in Java which counts how many a specific word occours in the string. The result will be printed on the console.

import java.util.Map;
import java.util.Scanner;
import java.util.HashMap;

public class Wordcounter {

    private Map<String, Integer> wordmap;

    public Wordcounter(){
        wordmap = new HashMap<String, Integer>();
        var wordlist = readWords();
        addWords(wordlist);
        printWordmap();
    }

    private String[] readWords(){
        Scanner sc = new Scanner(System.in);
        String text = sc.nextLine();
        String[] wordlist = text.split(" ");
        sc.close();
        return wordlist;
    }

    private void addWords(String[] wordlist){
        for(var n = 0; n < wordlist.length; n++){
            if(wordmap.containsKey(wordlist[n])){
                int count = wordmap.remove(wordlist[n]);
                count++;
                wordmap.put(wordlist[n], count);
            } else {
                wordmap.put(wordlist[n], 1);
            }
        }
    }

    private void printWordmap(){
        wordmap.forEach((k, v) -> System.out.println(k+" : "+v));
    }

    public static void main(String[] args){
        new Wordcounter();
    }
}



0
0
0.000
8 comments
avatar

ich versuch grad Python zu lernen. Vielleicht sollte ich meine Erkenntnisse auch hier posten.

0
0
0.000
avatar

Klar, warum nicht. Vielleicht hilft es anderen oder auch um ein Feedback zu bekommen.
!LUV

0
0
0.000
avatar

If i have to do the same with javascript pure i know that it is gonna be more difficult

0
0
0.000
avatar

yes, but javascript also has some advantages that Java does not have. It's much easier to write async code in js than in java for example.

0
0
0.000