Java, a word occour counter

in #hive-1635212 years ago

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();
    }
}

Sort:  

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

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

!BEER
!LUV
!PIZZA

@ozelot47, @jeyf123(1/1) sent LUV. | connect | community | HiveWiki | NFT | <>< daily

Hive General chat | Type ! help (no space) to get help on Hive. Info

Made with LUV by crrdlx

@jeyf123, @ozelot47(1/10) sent LUV. | connect | community | HiveWiki | NFT | <>< daily

Hive General chat | Type ! help (no space) to get help on Hive. Info

Made with LUV by crrdlx

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

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.

PIZZA!

$PIZZA slices delivered:
@jeyf123(1/5) tipped @ozelot47