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