I am trying to figure out how to find the most common word length in the british dictionary. I have inputted the text file for the british dictionary into my program. I tried a tedious way, but it doesn't seem effective. Can someone help me?
String longestWord = "";
int maxLength =0;
int count1 =0, count2 =0, count3=0, count4=0, count5=0, count6=0, count7=0, count8=0, count9=0, count10=0;
Scanner scanFile = new Scanner (new File("BritishDictionary.txt"));
ArrayList<String> book = new ArrayList<String>();
while(scanFile.hasNext())
{
book.add(scanFile.next());
for(int i =0; i<= book.size()-1;i++)
{
if(book.get(i).length()>longestWord.length())
{
maxLength = book.get(i).length();
longestWord = book.get(i);
}
}
for(int i =0; i<= book.size()-1; i++)
{
if(book.get(i).length() == 2)
{
count1++;
}
if(book.get(i).length()==3)
{
count2++;
}
if(book.get(i).length()==4)
{
count3++;
}
if(book.get(i).length() == 5)
{
count4++;
}
if(book.get(i).length() == 6)
{
count5++;
}
if(book.get(i).length() ==7)
{
count6++;
}
if(book.get(i).length() ==8)
{
count7++;
}
if(book.get(i).length()==9)
{
count8++;
}
if(book.get(i).length() ==10)
{
count9++;
}
if(book.get(i).length()==11)
{
count10++;
}
}
}
scanFile.close();
System.out.println("The longest word is:" + longestWord);
Hi buddy, please find the below java program
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws
java.lang.Exception
{
// Scanner object to read the Input
file
Scanner scanFile = new Scanner (new
File("BritishDictionary.txt"));
//HashMap to store count of strings
of certain lengths
HashMap<Integer,Integer> hm = new HashMap();
int wordLength=0,maxCount = 0;
while(scanFile.hasNext()){
String str = scanFile.next();
int l = str.length();
if(!hm.containsKey(l)){
hm.put(l,0);
}
//Add the length to the map
hm.put(l,hm.get(l)+1);
}
Set<Integer> key = hm.keySet();
//Iterate through all the elements in the map and find the
element
//With most number of occurances
for(Integer x : key){
if(hm.get(x)>maxCount){
maxCount = hm.get(x);
wordLength = x;
}
}
System.out.println("The most common word length is:" +
wordLength);
}
}
INPUT :
a a a adf afd
fd a dfsd adf df df f adf bdf cdf edf
OUTPUT :
The most common word length is:3
Get Answers For Free
Most questions answered within 1 hours.