Write an application that reads a line of text and prints a table indicating the
ID: 3726885 • Letter: W
Question
Write an application that reads a line of text and prints a table indicating the number of one-letter words, two-letter words, three-letter words, and so on, appearing in the text. For example, Fig a. shows the counts for the phrase
Whether 'tis nobler in the mind to suffer
Word length
Occurrences
1
0
2
2
3
1
4
2 (including 'tis)
5
0
6
2
7
1
Fig. a Word-length counts for the string "Whether 'tis nobler in the mind to suffer".
************************************************************************************************
in java please and thank you
Word length
Occurrences
1
0
2
2
3
1
4
2 (including 'tis)
5
0
6
2
7
1
Explanation / Answer
import java.util.Scanner;
public class CountWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a text: ");
String text = sc.nextLine();
sc.close();
// breaking text by space
String words[] = text.split("\s+");
// creating count array
int[] count = new int[100];
int maxLength = 0;
for(int i=0; i<words.length; i++) {
int len = words[i].length();
count[len]++;
if(len > maxLength)
maxLength = len;
}
System.out.println("Word Length Occurrences");
for(int i=1; i<=maxLength; i++)
System.out.println(i+" "+count[i]);
}
}
/*
Sample run:
Enter a text: Whether 'tis nobler in the mind to suffer
Word Length Occurrences
1 0
2 2
3 1
4 2
5 0
6 2
7 1
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.