import java.awt.Font;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/*
 * CountWords.java
 *
 * Created new on September 23, 2006, 6:55 PM
 *
 * COP 6007 Examples
 * 
 */

/**
 *
 * @author Bill Kraynek
 */
public class CountWords {
    
    /** Creates a new instance of CountWords */
    public CountWords() throws Exception {
        String fileName = JOptionPane.showInputDialog("Enter file name","src/CountWords.java");
        Scanner fileScanner = new Scanner(new File(fileName));
        // set up delimiters to be anything except a letter
        fileScanner.useDelimiter("[^a-zA-Z]+");
        int maxWordLength = 0;
        ArrayList<String> words = new ArrayList<String>();
        ArrayList<Integer> counts = new ArrayList<Integer>();
        while( fileScanner.hasNext() ) {
            String word = fileScanner.next();
            if( words.contains(word) ) {
                int wordIndex = words.indexOf(word);
                counts.set(wordIndex,counts.get(wordIndex)+1);
            } else {
                words.add(word);
                if( word.length() > maxWordLength ) maxWordLength = word.length();
                counts.add(1);
            }// end if
        }// end while
        JTextArea outArea = new JTextArea(25,40);
        // need a monospaced font for columns to line up
        Font myFont = new Font("monospaced", Font.BOLD, 20);
        outArea.setFont(myFont);
        String blanks = "";
        for( int i = 0; i < maxWordLength + 1; i++ ) blanks += " ";
        String out = "Words" + blanks.substring(8) + "Count\n\n";
        for( int i = 0; i < words.size(); i++ ) {
            int count = counts.get(i);
            out += words.get(i) + blanks.substring(words.get(i).length() + (count+"").length()) + count + "\n";
        }// end for
        outArea.setText(out);
        JOptionPane.showMessageDialog(null, new JScrollPane(outArea));
    } // end constructor
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        new CountWords();
    } // end main
    
}// end CountWords

