Read the question, write Java on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Read a line of words; print each word and count alphabetically.
Examples
Input
the cat the dog the
Output
cat 1 dog 1 the 3
Hint
- TreeMap<String,Integer>
Show correct code
Peek only after you have tried. You can still Check your own version.
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] words = in.nextLine().trim().split("\\s+");
TreeMap<String, Integer> map = new TreeMap<>();
for (String w : words) if (!w.isEmpty()) map.merge(w, 1, Integer::sum);
for (var e : map.entrySet()) System.out.println(e.getKey() + " " + e.getValue());
}
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.