THINK FIRST·CODE LATER

← All labs

Word-frequency report

Problem

Read a text from standard input (any number of lines, possibly none) and produce a word-frequency report.

  • A word is a maximal run of letters az, after converting the whole text to lower case. Everything else (spaces, digits, punctuation) separates words, so "don't" gives don and t.
  • Count every word with a Map, and print the report in alphabetical order — let a TreeMap do the sorting.
  • The most frequent word is the one with the highest count; on a tie, the alphabetically first one wins. If there are no words, print none.

For the input

To be, or not to be: that is the question.

the output must be exactly:

Total words: 10
Distinct words: 8
be: 2
is: 1
not: 1
or: 1
question: 1
that: 1
the: 1
to: 2
Most frequent: be (2)

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.