Skip to content

Commit cef00a7

Browse files
author
jsquared21
committedOct 4, 2015
Add Ex 18.15
1 parent 9c287b7 commit cef00a7

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
 

Diff for: ‎Exercise_18/Exercise_18_15/Exercise_18_15.class

1.3 KB
Binary file not shown.

Diff for: ‎Exercise_18/Exercise_18_15/Exercise_18_15.java

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

Comments
 (0)