I'm trying to create a recursive method to find the number of occurrences of an UpperCase letter in a String. My code below:
public class findUppercase {
public static int searchUppercase(String s, int high) {
if (s.length() == 1) {
if (Character.isUpperCase(s.charAt(0)))
return 1;
else
return 0;
} else if (Character.isUpperCase(s.charAt(high - 1)) )
return 1 + searchUppercase(s, s.length() - 1);
else
return searchUppercase(s, s.length() - 1);
}
public static int searchUppercase(String s) {
return searchUppercase(s, s.length());
}
public static void main(String[] args) {
String a = "ABCmdsaA";
System.out.println(searchUppercase(a));
}
}
I get the error:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.Character.getType(Character.java:6924)
at java.lang.Character.isUpperCase(Character.java:5518)
at java.lang.Character.isUpperCase(Character.java:5488)
at findUppercase.searchUppercase(findUppercase.java:9)
As your String is never changing, its length will never change, so
if (s.length() == 1) {
will never be true unless you originally pass in a one char String
Change the value of the String s
by using String.substring
Although personally I would just use a for
loop and not a recursive method.