Skip to content

Commit dee18cb

Browse files
author
jsquared21
committedOct 4, 2015
Add Ex 18.14
1 parent 3302f77 commit dee18cb

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
 
1.25 KB
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*********************************************************************************
2+
* (Find the number of uppercase letters in a string) Write a recursive method to *
3+
* return the number of uppercase letters in a string. Write a test program that *
4+
* prompts the user to enter a string and displays the number of uppercase *
5+
* letters in the string. *
6+
*********************************************************************************/
7+
import java.util.Scanner;
8+
9+
public class Exercise_18_14 {
10+
/** Main method */
11+
public static void main(String[] args) {
12+
// Create a Scanner
13+
Scanner input = new Scanner(System.in);
14+
15+
// Prompt the user to enter a string
16+
System.out.print("Enter a string: ");
17+
String str = input.nextLine();
18+
19+
// Display the number of uppercase letters in the string
20+
System.out.println("There are " + countUppercase(str)
21+
+ " uppercase letters in \"" + str + "\".");
22+
}
23+
24+
/** Method counts the uppercase letters in a string */
25+
public static int countUppercase(String str) {
26+
int count = 0;
27+
int index = str.length() - 1;
28+
return countUppercase(str, index, count);
29+
}
30+
31+
/** Helper method */
32+
private static int countUppercase(String str, int index, int count) {
33+
if (index < 0) // Base case
34+
return count;
35+
else if (Character.isUpperCase(str.charAt(index)))
36+
return countUppercase(str, index - 1, count + 1); // Recursive call
37+
else
38+
return countUppercase(str, index - 1, count); // Recursive call
39+
}
40+
}

0 commit comments

Comments
 (0)
Please sign in to comment.