I’m doing an online CPS course and a question requires me to write a code that counts the vowels(upper and lowercase) in a string. Here is my code:
public static int countVowels( String s )
{
{
if ( s.length() == 0 )
return 0 + countVowels(s);
else if ( (s.substring(0, 1) == "a" ) || (s.substring(0, 1) == "A") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "e" ) || (s.substring(0, 1) == "E") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "i" ) || (s.substring(0, 1) == "I") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "o" ) || (s.substring(0, 1) == "O") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "u" ) || (s.substring(0, 1) == "U") )
return 1 + countVowels(s.substring(1));
}
return countVowels(s.substring(1));
}
but I’m getting a “StackOverFlow” error and I’m not sure what to do. I know that the error means that the terminating condition isn’t being reached. I’m not allowed to use anything that I haven’t learned yet and I’m also not allowed to use for or while statements because this is a recursion problem.
Could I please get some help?
In the case when
s.length() == 0you are causing an infinite recursion. An empty string has 0 vowels, so you should edit 5th line toreturn 0;Another thing to watch out for: you’re comparing strings with==. This operator is intended for something else. Useequalsinstead. Take a look at this, for example: String comparison. That iss.substring(0, 1) == "a"should becomes.substring(0, 1).equals("a")As a matter of fact, there are some other pieces of advice I’d give you, like just storing the first letter in the string, instead of calculating it in every case (twice at that). Also, you can get the lower case character for the first character, so that you can reduce the cases you compare to twice. Also, add vowels to an array, this code is not DRY.