import java.awt.Font; import java.io.File; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; /* * CountWordsExerciseSolution.java * * Created on October 2, 2005, 3:06 PM * */ /** * * @author Bill Kraynek */ public class CountWordsExerciseSolution { /** Creates a new instance of CountWordsExerciseSolution */ public CountWordsExerciseSolution() throws Exception { String fileName = JOptionPane.showInputDialog("Enter file name","src/CountWordsExerciseSolution.java"); Scanner fileScanner = new Scanner(new File(fileName)); // set up delimiters to be anything except a letter fileScanner.useDelimiter("[^a-zA-Z]+"); ArrayList words = new ArrayList(); ArrayList counts = new ArrayList(); 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); counts.add(1); }// end if }// end while JTextArea outArea = new JTextArea(30,40); // need a monospaced font for columns to line up Font myFont = new Font("monospaced", Font.BOLD, 20); outArea.setFont(myFont); // need blanks for spacing String blanks = ""; for( int i = 0; i < 30; i++ ) blanks += " "; String out = "Words" + blanks.substring(5) + "Count\n\n"; for( int i = 0; i < words.size(); i++ ) { out += words.get(i) + blanks.substring(words.get(i).length()) + counts.get(i) + "\n"; }// end for outArea.setText(out); JOptionPane.showMessageDialog(null, new JScrollPane(outArea)); } /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { new CountWordsExerciseSolution(); } }