/**
 * Count the number of words in a file two ways and compare the time elapsed.
 *
 * @author	Terry Sergeant
 * @version for P2
 *
 * NOTE: This file uses a structured programming approach of handling the timing
 * of the code. Contrast this with CountWordsOOP.java.
*/

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileInputStream;
import java.util.Scanner;

public class CountWordsStructured
{
	public static void main(String [] args) throws Exception
	{
		long start1,stop1; // for tracking time elapsed when using Scanner
		long start2,stop2; // for tracking time elapsed when using BufferedReader
		int wordCount1;    // number of words read from file using Scanner
		int wordCount2;    // number of words read from file using BufferedReader
		int charCount1;    // number of characters in words read from file using Scanner
		int charCount2;    // number of characters in words read from file using BufferedReader
		String word;       // word most recently read from the file


		// Read words using Scanner and count them and measure how long it takes
		start1= System.currentTimeMillis();
		wordCount1= 0;
		charCount1= 0;
		Scanner wordfile1= new Scanner(new FileInputStream("words.txt"));
		while (wordfile1.hasNextLine()) {
			word= wordfile1.nextLine();
			charCount1+= word.length();
			wordCount1++;
		}
		wordfile1.close();
		stop1= System.currentTimeMillis();


		// Read words using BufferedReader and count them and measure how long it takes
		start2= System.currentTimeMillis();
		wordCount2= 0;
		charCount2= 0;
		BufferedReader wordfile2= new BufferedReader(new FileReader("words.txt"));
		while ((word= wordfile2.readLine()) != null) {
			charCount2+= word.length();
			wordCount2++;
		}
		wordfile2.close();
		stop2= System.currentTimeMillis();


		// display results
		System.out.printf("Word Count (Scanner)        : %d\n",wordCount1);
		System.out.printf("Word Count (BufferedReader) : %d\n",wordCount2);
		System.out.printf("Char Count (Scanner)        : %d\n",charCount1);
		System.out.printf("Char Count (BufferedReader) : %d\n",charCount2);
		System.out.println("------------------------------------------");
		System.out.printf("Time (Scanner)              : %1.3f seconds\n",(stop1-start1)/1000.0);
		System.out.printf("Time (BufferedReader)       : %1.3f seconds\n",(stop2-start2)/1000.0);
	}
}
