Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package edu.upenn.cis.cis121.homework3;
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.ArrayList;
- /**
- * An implementation of the UNIX word count utility wc.
- *
- * @author Josh Margolis
- * CIS 121, Spring 2012
- *
- */
- public class WordCount {
- /**
- * Static method that processes the input.
- * @param fileName - the name of the file to be opened
- * @return String output formatted string specifying number of lines, words, and characters
- * @throws IOException
- **/
- public static String processFile(String fileName) throws IOException{
- BufferedReader bReader = new BufferedReader(new FileReader(fileName));
- //holds if we are in a word or not, other variables are self-explanatory
- boolean inWord = false;
- int numChars = 0;
- int numWords = 0;
- int numLines = 0;
- //The current line we are in
- String line = "";
- while((line = bReader.readLine()) != null){
- numLines++;//Add to line
- numChars++;//Add to char because the line character will not be counted otherwise
- for (int i = 0; i<line.length(); i++) {
- numChars++;
- if(line.charAt(i) == '\t' || line.charAt(i) == ' '){
- //Check if were in a word
- if(inWord){
- numWords++;
- inWord = false;
- }
- }
- else
- inWord = true;
- }
- }
- //Add one more if are still in a word
- if(inWord == true)
- numWords++;
- bReader.close();//Clean up
- return (numLines + "\t" + numWords + "\t" + numChars + "\t" + fileName);
- }
- /**
- * Program that takes a list of filenames as a command-line argument.
- * For each file, program should output number of lines, words, and characters
- * in the file. If no filename is provided, report that a filename argument is required
- **/
- public static void main(String args[]) {
- ArrayList<String> rtnInfo = new ArrayList<String>();
- for(String arg : args)
- try {
- //txtReader = new InputStreamReader(new FileInputStream (arg), "US-ASCII");
- //rtnInfo.agdd(processInput(txtReader) + "\t" + arg);
- rtnInfo.add(processFile(arg));
- } catch (IOException e) {
- // Die, comment this out later
- System.out.println("File Error...");
- }
- //Build the total numbers
- int totals[] = {0,0,0};
- for(String x: rtnInfo){
- System.out.println(x);
- for(int i = 0; i < 3; i++)
- totals[i] += Integer.parseInt(x.split("\t")[i]);
- }
- //Print the totals
- System.out.println(totals[0] + "\t" + totals[1] + "\t" + totals[2]);
- }
- }
Add Comment
Please, Sign In to add comment