Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Word count in Java

807588May 24 2009 — edited May 25 2009
Hello everyone!

I am trying to write a program to count the number of words in a file called output.txt, that is just a document with separate words line by line. I need to figure out the most frequent 25 words and the most frequent 25 words that start with the letter F. Also the prof. asked for the total number of words and the total number of unique words... I have no idea how to do this.

My friend helped me to write this code, that doesnt really work that well
import java.util.*; // Provides TreeMap, Iterator, Scanner
import java.io.*; // Provides FileReader, FileNotFoundException

public class WordCounter
{
public static void main(String[] args)
{
TreeMap<String, Integer> frequencyData = new TreeMap<String, Integer>( );

readWordFile(frequencyData);
printAllCounts(frequencyData);
}

public static int getCount(String word, TreeMap<String, Integer> 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<String, Integer> 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<String, Integer> 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("output"));
}
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);
}
}

}
This is the error:+_

run:
java.io.FileNotFoundException: output (The system cannot find the file specified)
-----------------------------------------------
Occurrences Word
-----------------------------------------------
BUILD SUCCESSFUL (total time: 0 seconds)

Please help!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 22 2009
Added on May 24 2009
16 comments
593 views