In: Computer Science
Hello! I am having trouble starting this program in Java.
the objective is as follows:
" I will include a text file with this assignment. It is a text version of this assignment.
Write a program that will read the file line by line, and break each line into an array of words using the tokenize method in the String class. Count how many words are in the file and print out that number. "
my question is, how do i start this program? I know i can use the following snippet of code to read the text line by line,
BufferedReader reader = new BufferedReader(new StringReader(<string>)); reader.readLine();
but, I am unsure how to actually use the tokenize class, I am using the book intro to Java prog by Liang but i am not seeing an example similar that calls for the txt to be read and to count and print them.
Java Program:
/* Java Program that reads data from file and counts number of words in the file using String tokenizer class */
import java.io.*;
import java.util.*;
//Class definition
class StringTokenizerDemo
{
//Main method
public static void main(String[]args) throws
IOException
{
String line;
int words = 0;
//Opening file for reading
FileReader fin = new
FileReader("inputFile.txt");
//Reader class to read data from
file
BufferedReader reader = new
BufferedReader(fin);
//Iterate till all lines are
processed
while ( ( line = reader.readLine()
) != null )
{
//Tokenizing
line into words using space delimiter
StringTokenizer
st = new StringTokenizer(line," ");
//Counting
number of words in the line
while
(st.hasMoreTokens())
{
//Getting next token
st.nextToken();
//Incrementing number of words
words += 1;
}
}
//Closing file
fin.close();
//Printing number of words
System.out.println("\n\n Total
number of words in the file: " + words);
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sample Output: