Solution Review: Let's find the total number of vowels!
This lesson provides a detailed review of the solution to the challenge in the previous lesson.
We'll cover the following...
Solution: How many vowels are there?
Press + to interact
class ChallengeClass {public static int totalVowels(String text, int len, int index) {int count = 0;if (len == 0) {return 0;}char single = Character.toUpperCase(text.charAt(index));if (single == 'A' || single == 'E' || single == 'I' || single == 'O' || single == 'U') {count++;}return count + totalVowels(text, len-1, index+1);}public static int callTotalVowels(String text) {return totalVowels(text, text.length(), 0);}public static void main( String args[] ) {String string1 = "Hello world";String string2 = "STR";String string3 = "AEIOUaeiouSs";int result1 = callTotalVowels(string1);int result2 = callTotalVowels(string2);int result3 = callTotalVowels(string3);System.out.println( "Total number of vowels in " + string1 + " are = " + result1);System.out.println( "Total number of vowels in " + string2 + " are = " + result2);System.out.println( "Total number of vowels in " + string3 + " are = " + result3);}}
Understanding the Code
Every recursive code has two methods; the recursive method and the main method.
Driver Method
The recursive method is called within the driver method. Let’s first look at what it does-from line 21 to line 31.
- There are three calls made to the recursive method. Each call, prints the given string and the total number of vowels within it.