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 a–z, 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)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d5-1-data-1.txt

To be, or not to be: that is the question.
What your program must print for d5-1-data-1.txt
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)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d5-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content d5-1-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

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.