Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that will read in a line of text and output the number of words

ID: 3640418 • Letter: W

Question

Write a program that will read in a line of text and output the number of words in the line and the frequency of each letter, both as a count and as a relative frequency within the text. Define a word to be any string of letters that is delimited at each end by either white space, a period, a comma, or the beginning or end of the line. You can assume the input consists of only letters, periods, commas, and whitespace. For example, the input

They say Hello.

should output something similar to the following:

3 words
A 1 8.333333%
E 2 16.666667%
H 2 16.666667%
L 2 16.666667%
O 1 8.333333%
S 1 8.333333%
T 1 8.333333%
Y 2 16.666667%


Ensure the output is in sorted order. It is up to you on how to do this.

Explanation / Answer

public static void main(String[] args)
{
// read in line of text
System.out.print("Enter line: ");
Scanner kb = new Scanner(System.in);

String line = kb.nextLine();

String[] split = line.split("[.\s,]+");
System.out.println(split.length()+" words");

int[] counts = new int[26];
int total = 0;
for(char c : line.toCharArray())
{
if(Character.isLetter(c))
{
counts[Character.toUpperCase(c)-'A'] ++;
total++;
}
}

// print counts
for(int i = 0; i < counts.length; i++)
{
if(counts[i] > 0)
{
System.out.println((char)('A'+i)+" "+counts[i]+" "+((double)counts[i]/total);
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote