Paul,
I suggest you read through this old thread: Java BufferedReader back to the top of a text file?.
Personally I prefer Jon Skeet's response, which boils down to "Don't bother [unless you MUST]."
Cheers. Keith.
EDIT: Also you should ALLWAYS close that input file, even if you hit an Exception. The finally
block is perfect for this.
EDIT2:
Hope you're still with us.
Here's my attempt, and FWIW, you DON'T need to reset the input-file, you just need to transpose your while
and for
loops.
package forums;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordOccurrenceCount
{
public static void main(String[] args) {
try {
String[] words = { "and", "is", "a", "the", "of", "as" };
int[] occurrences = readOccurrences("C:/tmp/prose.txt", words);
for ( int i=0; i<words.length; i++ ) {
System.out.println(words[i] + " " + occurrences[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static final int[] readOccurrences(String filename, String... words)
throws IOException
{
int[] occurrences = new int[words.length];
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
Scanner scanner = new Scanner(reader);
while ( scanner.hasNext() ) {
String word = scanner.next();
for ( int i=0; i<words.length; i++ ) {
if ( words[i].equals(word) ) {
occurrences[i]++;
}
}
}
} finally {
if(reader!=null) reader.close();
}
return occurrences;
}
}
And BTW, java.util.Map is perfect for building a frequency table... Parallel arrays are just SOOOOO 90's. The "default" implementation of Map is the HashMap
class... By default I mean use HashMap whenever you need a Map, unless you've got a good reason to use something else, which won't be often. HashMap is generally the best allround performer.