import java.awt.Font; import java.io.File; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * * @author Bill Kraynek */ public class CountWordsWithWordClassUsingArrays { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { Scanner fileScanner = new Scanner(new File("src/CountWordsWithWordClassUsingArrays.java")); fileScanner.useDelimiter("[^A-Za-z]+"); WordClass[] words = new WordClass[20]; int wordsSize = 0; while (fileScanner.hasNext()) { WordClass word = new WordClass(fileScanner.next()); int index = indexOf(words, wordsSize, word); if (index == -1) { if (wordsSize == words.length) { words = increaseCapacity(words); } words[wordsSize] = word; wordsSize++; } else { words[index].incrementCount(); }// end if }// end while words = trim(words, wordsSize); display(words); Arrays.sort(words); display(words); Arrays.sort(words, new WordClass.CountWordsComparator()); display(words); }// end main static int indexOf(WordClass[] words, int wordsSize, WordClass word) { for (int i = 0; i < wordsSize; i++) { if (words[i].equals(word)) { return i; } }// end for return -1; }// end indexOf static WordClass[] increaseCapacity(WordClass[] array) { WordClass[] save = array; array = new WordClass[2 * array.length + 1]; for (int i = 0; i < save.length; i++) { array[i] = save[i]; }// end for return array; }// end increaseCapacity static WordClass[] trim(WordClass[] words, int wordsSize) { WordClass[] save = words; words = new WordClass[wordsSize]; for (int i = 0; i < wordsSize; i++) { words[i] = save[i]; } return words; }// end trim static void display(WordClass[] words) { String out = ""; for (int i = 0; i < words.length; i++) { out += words[i]; }// end for JTextArea outArea = new JTextArea(out, 40, 40); outArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 15)); JOptionPane.showMessageDialog(null, new JScrollPane(outArea)); } }