Monday, September 8, 2008

Count Number Of Words In A Given File

import java.util.*; // Provides TreeMap, Iterator, Scanner
import java.io.*; // Provides FileReader, FileNotFoundException

public class CountNumOfWords
{
public static void main(String[] args) 
TreeMap frequencyData = new TreeMap( );

readWordFile(frequencyData); 
printAllCounts(frequencyData);
}

public static int getCount(String word, TreeMap frequencyData)
{
if (frequencyData.containsKey(word))
{ // The word has occurred before, so get its count from the map
return frequencyData.get(word); // Auto-unboxed
}
else
{ // No occurrences of this word
return 0;
}
}

public static void printAllCounts(TreeMap frequencyData)
{
System.out.println("-----------------------------------------------");
System.out.println(" Occurrences Word");

for(String word : frequencyData.keySet( ))
{
System.out.printf("%15d %s\n", frequencyData.get(word), word);
}

System.out.println("-----------------------------------------------");

public static void readWordFile(TreeMap frequencyData)
{
Scanner wordFile;
String word; // A word read from the file
Integer count; // The number of occurrences of the word

try
{
wordFile = new Scanner(new FileReader("c:/Profile.java"));
}
catch (FileNotFoundException e)
{
System.err.println(e);
return;
}

while (wordFile.hasNext())
{
// Read the next word and get rid of the end-of-line marker if needed:
word = wordFile.next();

// Get the current count of this word, add one, and then store the new count:
count = getCount(word, frequencyData) + 1;
frequencyData.put(word, count);
}

}

No comments: