NumOccur.java

Download
1/*2 * NumOccur.java3 *4 * Computer Science S-225 *6 * A class that contains a recursive method for determining the7 * number of times that a character appears in a string.8 *9 * The main method includes two examples of using this method.10 *11 * You can also test this method by entering12 * NumOccur.numOccur(ch, str) -- where ch is replaced by a char13 * and str is replaced by a string -- from the Interactions Pane.14 */15 16public class NumOccur {17    /*18     * numOccur - a recursive method that returns the number of times 19     * that the character ch occurs in the String str.20     */21    public static int numOccur(char ch, String str) {22        // base case23        if (str == null || str.equals("")) {24            return 0;25        }26    27        // recursive case28        int numOccurInRest = numOccur(ch, str.substring(1));29        if (ch == str.charAt(0)) {30            return 1 + numOccurInRest;31        } else {32            return numOccurInRest;33        }34    }35    36    public static void main(String[] args) {37        System.out.println("numOccur('s', \"Mississippi\") = " +38          numOccur('s', "Mississippi"));39        System.out.println("numOccur('e', \"Mississippi\") = " +40          numOccur('e', "Mississippi"));                   41    }42}