1
+ /**********************************************************************************
2
+ * (Occurrences of a specified character in a string) Rewrite Programming Exercise *
3
+ * 18.10 using a helper method to pass the substring high index to the method. *
4
+ * The helper method header is: *
5
+ * *
6
+ * public static int count(String str, char a, int high) *
7
+ **********************************************************************************/
8
+ import java .util .Scanner ;
9
+
10
+ public class Exercise_18_15 {
11
+ /** Main method */
12
+ public static void main (String [] args ) {
13
+ // Create a Scanner
14
+ Scanner input = new Scanner (System .in );
15
+
16
+ // Prompt the user to enter a string and a character
17
+ System .out .print ("Enter a string and a character: " );
18
+ String [] str = input .nextLine ().split ("[ ]" );
19
+
20
+ // Display the number of times the character occurs in the string
21
+ System .out .println ("The character \' " + str [1 ] + "\' occurs " +
22
+ count (str [0 ], str [1 ].charAt (0 )) + " times in \" " + str [0 ] + "\" ." );
23
+ }
24
+
25
+ /** Method counts the number of occurrences
26
+ * of a specified character in a string */
27
+ public static int count (String str , char a ) {
28
+ return count (str , a , str .length () - 1 );
29
+ }
30
+
31
+ /** Helper melthod used to pass the substring high index */
32
+ private static int count (String str , char a , int high ) {
33
+ if (high < 0 ) // Base case
34
+ return 0 ;
35
+ else if (str .charAt (high ) == a ) {
36
+ return 1 + count (str , a , high - 1 ); // Recursive call
37
+ }
38
+ else
39
+ return count (str , a , high - 1 ); // Recursive call
40
+ }
41
+ }
0 commit comments