Skip to main content

Java Advanced WordCount application

1 reply [Last post]
Joined: 2006-02-14
Points: 0


I've worked on doing an application to read a txt file, then print back the number of characters, words and the number of lines in the text file. Once thats been done the application must then be able to output the number of occurences of each word in the text file and on how many lines each word is:
the quick brow fox jumped over the
lazy dog
This would give:
2 occurences of "the"
1 line contains "the"

I'm new to java and i've managed to get the number of lines to report back but i'm not sure on how to get the rest done. I've explored using the StringTokenizer mthod to achieve my results but i'm finding it very difficult to code. If anyone has a chance to take a look here's the code i've been able to do:

import java.util.*;

class WordCounter {

// Main

public static void main (String[] args) {
WordCounter t = new WordCounter();

// Read the file and output

void fileRead() {

String record = null;
int numLines = 0;
int numWords = 0;
int numChars = 0;

try {

FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);

record = new String();
while ((record = br.readLine()) != null) {


// Output values

System.out.println("Number of lines:" + numLines);
System.out.println("Number of words:" + numWords);
System.out.println("Number of chars:" + numChars);

} catch (IOException e) {

// Catch possible io errors from readLine()

System.out.println("IOException error!");

} // End of fileRead

} // End of class

Thanks if anyone can help me with this it's been annoying me now for a long time.


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2006-02-14
Points: 0

To count the words:

StringTokenizer parser = new StringTokenizer(text);
int count = 0;
while (parser.hasMoreTokens()) {
String word = parser.nextToken();