// CharCounter.java // A solution to CS 5JA assignment 5, part 2, Winter 2009 // updated by cmc, 2/24/09 // Note: the javadoc comments are not required. /** Provides various counts of the characters in an array. */ public class CharCounter { private char[] array; /** Only constructor associates this CharCounter object with an existing array of characters. The array is not copied - therefore any changes made to the array elements after a CharCounter object is constructed may affect any or all of the counts provided. @param theArray the array of characters to count. */ public CharCounter(char[] theArray) { array = theArray; // Note: above statement is all that is required. Below is just an // example of the type of steps programmers take to protect their // code from crashing. Here it is to avoid NullPointerExceptions // in the methods that follow. if (array == null) array = new char[0]; } /** Provides the total count of characters (same as the array's length). @return total number of characters in the array. */ public int count() { return array.length; } /** Provides the count of a particular character. @param c the character to count. @return the number of occurrences of the value of c in the array. */ public int count(char c) { int result = 0; for (char ac : array) if (ac == c) ++result; return result; } /** Provides the counts of each of an array of particular characters. @param c the array of characters to count. @return the number of occurrences (in the array referenced by this CharCounter object) of each value in array c, in the same order as the characters in c. */ public int[] countEach(char[] c) { int results[] = new int[c.length]; for (int i = 0; i < c.length; i++) results[i] = count(c[i]); return results; } /** Provides the total count of letter characters (A-Z, a-z). @return the number of occurrences of letter chars in the array. */ public int countLetters() { int result = 0; for (char c : array) if ( isLetter(c) ) ++result; return result; } // utility method identifies a letter char private boolean isLetter(char c) { return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'; } /** Provides the total count of digit characters (0-9). @return the number of occurrences of digit chars in the array. */ public int countDigits() { int result = 0; for (char c : array) if ( isDigit(c) ) ++result; return result; } // utility method identifies a digit char private boolean isDigit(char c) { return c >= '0' && c <= '9'; } /** Provides the total count of other characters (not letters or digits). @return the number of occurrences of other chars in the array. */ public int countOther() { int result = 0; for (char c : array) if ( isOther(c) ) ++result; return result; } // utility method identifies a character that is neither letter nor digit private boolean isOther(char c) { return !isLetter(c) && !isDigit(c); } }