import java.io.File;
import java.util.Scanner;
// 12345. has a length 6 Should all punctuation be removed? Maybe just .?!() and "
// What is the word length of her's 3, 4, or 5?
// maybe not print stats for lengths that have no words
public class CountWords {
private static int[] wordCount = new int[15];
private static int total_words = 0;
public CountWords() {
for (int i = 0; i < wordCount.length; i++)
wordCount[i] = 0;
total_words = 0;
}
public String toString() {
String ret = "";
for (int i = 1; i < wordCount.length; i++)
ret = ret + String.format("Proportion of %d-letter words is %2.1f%% (%d words)\n",i,
(wordCount[i]*1.0/total_words)*100, wordCount[i]);
ret = ret + String.format("Proportion of %d-letter(or more) words is %2.1f%% (%d words)\n",wordCount.length,
(wordCount[0]*1.0/total_words)*100, wordCount[0]);
return ret;
}
public static void addWord(String word) {
if (word.length() < 1) // skip it
return;
else if (word.length() >= wordCount.length) // too big
wordCount[0]++;
else // worth counting
wordCount[word.length()]= wordCount[word.length()]+1;
total_words++;
}
public static void processFile (Scanner input) {
while (input.hasNextLine())
{
String line = input.nextLine();
// split the line into an array of words
String[] arr = line.split(" "); // translate punct into spaces first?
// loop thru the array -
// look at the length of each word
// count how many words of that length we have seen
for ( String ss : arr) {
//System.out.println("Process " + ss + " length = " + ss.length());
addWord(ss);
}
} // while
}
public static void main(String[] args) {
fileUtils a = new fileUtils(); // use getScanner
CountWords c = new CountWords();
Scanner sc = null;
if (args.length > 0)
sc = a.getScanner(args[0]);
else
sc = a.getScanner("");
c.processFile(sc);
System.out.println(c.toString());
sc.close();
} // main
} // fileUtils
|