w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do you find words in a text file and print the most frequent word shown using array?

Consider using a Map<String,Integer> for the word then you can implement this to count words and will be work for any number of words. See Documentation for Map.

Like this (would require modification for case insensitive)

public Map<String,Integer> words_count = new
HashMap<String,Integer>();

//read your line (you will have to determine if this line should be split
or is equations
//also just noticed that the trailing '!' would need to be removed

String[] words = line.split("\s+");
for(int i=0;i<words.length;i++)
{
     String s = words[i];
     if(words_count.ketSet().contains(s))
     {
          Integer count = words_count.get(s) + 1;
          words_count.put(s, count)
     }
     else
          words_count.put(s, 1)

}

Then you have the number of occurrences for each word in the string and to get the most occurring do something like

Integer frequency = null;
String mostFrequent = null;
for(String s : words_count.ketSet())
{
    Integer i = words_count.get(s);
    if(frequency == null)
         frequency = i;
    if(i > frequency)
    {
         frequency = i;
         mostFrequent = s;
    }
}

Then to print

System.out.println("The word "+ mostFrequent +" occurred "+
frequency +" times");




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.