// CharCounterTest.java // Use AS-IS to test CS 5JA assignment 5, part 2 // updated by cmc, 2/24/09 import java.util.Scanner; public class CharCounterTest { public static void main(String[] args) { System.out.println( "Enter text. End by ctrl-Z (Windows) or ctrl-D (other)."); // utility method (below main) gets the text and stores in array char text[] = getText(); CharCounter ctr = new CharCounter(text); System.out.printf("%nTotal chars = %,d%n%n", ctr.count()); System.out.println("Letters"); char upper = 'A', lower = 'a'; while (upper <= 'Z') { int sum = ctr.count(upper) + ctr.count(lower); if (sum > 0) System.out.printf("\t%c, %c: %,d%n", upper, lower, sum); ++upper; ++lower; } System.out.printf("\ttotal letters: %,d%n%n", ctr.countLetters()); System.out.println("Digits"); for (char c = '0'; c <= '9'; c++) { int n = ctr.count(c); if (n > 0) System.out.printf("\t%c: %,d%n", c, n); } System.out.printf("\ttotal digits: %,d%n%n", ctr.countDigits()); System.out.println("Miscellaneous"); char punct[] = { '.', ',', ':', ';', '!', '?' }, symbols[] = { '@', '#', '$', '%', '&' }; int pCounts[] = ctr.countEach(punct), sCounts[] = ctr.countEach(symbols); for (int i = 0; i < punct.length; i++) if (pCounts[i] > 0) System.out.printf("\t\'%c\': %,d%n", punct[i], pCounts[i]); for (int i = 0; i < symbols.length; i++) if (sCounts[i] > 0) System.out.printf("\t\'%c\': %,d%n", symbols[i], sCounts[i]); System.out.printf("\tspaces: %,d%n", ctr.count(' ')); System.out.printf("\tnewlines: %,d%n", ctr.count('\n')); System.out.printf("\ttotal, except letters and digits: %,d%n", ctr.countOther()); } // utility accumulates the text into char array private static char[] getText() { Scanner input = new Scanner(System.in); StringBuilder sb = new StringBuilder(); while ( input.hasNextLine() ) { sb.append(input.nextLine()); sb.append('\n'); // replace the newline } return sb.toString().toCharArray(); } }