
write a program that reads in a text typed in by the user and produces a list of disinct words in alphabetical order and how many times each word appears in the passage.

The given code accepts the string text from the user and display distinct words in ascending order. The code also displays the frequency of each word.
import java.util.*;
public class CountWordOccurrence {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter string: ");
String str=input.nextLine();
HashMap<String, Integer> map = new HashMap<String, Integer>();
str = str.toLowerCase();
int count = -1;
for (int i = 0; i < str.length(); i++) {
if ((!Character.isLetter(str.charAt(i))) || (i + 1 == str.length())) {
if (i - count > 1) {
if (Character.isLetter(str.charAt(i)))
i++;
String word = str.substring(count + 1, i);
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
}
else{
map.put(word, 1);
}
}
count = i;
}
}
List sortedKeys=new ArrayList(map.keySet());
Collections.sort(sortedKeys);
System.out.println("List of words in ascending order: ");
for(int i=0;i<sortedKeys.size();i++){
System.out.println(sortedKeys.get(i).toString());
}
for(Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey()+" : "+ entry.getValue());
}
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.