I want to display the words in ascending order of occurrence counts.
In addition I would like to simplify my main method.
Any suggestions? Thanks.
// import
import java.util.*;
import java.io.*;
// program
public class Program
{
// main
public static void main(String[] args) throws IOException
{
try
{
// read file, file is passed as argument
BufferedReader read = (new BufferedReader(new FileReader(args[0])));
// declare variables
String stream = null;
TreeMap<String,Integer> store = new TreeMap<String,Integer>();
// count words in case-insensitive fashion, do not count
// word if the first character is not a letter
while ((stream = read.readLine()) != null)
{
// delimited special characters and spaces
String[] text = stream.split("[ ,:.:?'\"()]");
for (int i = 0; i < text.length; i++)
{
String token = text[i].toLowerCase();
if (token.length() > 0)
{
if (store.get(token) == null)
{
store.put(token,1);
}
else
{
int val = store.get(token).intValue();
val++;
store.put(token,val);
}
}
}
}
// display output in alphabetical order of words with each
// proceeded by its occurrence count
// put entries in set
Set<Map.Entry<String,Integer>> entrySet = store.entrySet();
// get token and val from each entry
System.out.println("\nCount:\t"+ "\tWords:\n");
for (Map.Entry<String,Integer> entry: entrySet)
{
System.out.println(entry.getValue() + "\t\t" + entry.getKey());
}
// display the words in ascending order of occurrence counts
}
catch (Exception x)
{
x.printStackTrace();
}
}
}

New Topic/Question
Reply



MultiQuote



|