NumOccur.java

Download
1/*2 * NumOccur.java3 *4 * Computer Science E-22/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 12public class NumOccur {13    /*14     * numOccur - a recursive method that returns the number of times 15     * that the character c occurs in the String s.16     */17    public static int numOccur(char c, String s) {18        if (s == null || s.equals("")) {   // base case19            return 0;20        } else {                           // recursive case21            int numInRest = numOccur(c, s.substring(1));22            if (s.charAt(0) == c) {23                return 1 + numInRest;24            } else {25                return numInRest;26            }27        }28    }29    30    public static void main(String[] args) {31        System.out.println("numOccur('s', \"Mississippi\") = " +32          numOccur('s', "Mississippi"));33        System.out.println("numOccur('e', \"Mississippi\") = " +34          numOccur('e', "Mississippi"));                   35    }36}