131k views
1 vote
Create a recursive method, a method that calls itself, that returns the number of vowels that appear in any string given. Keep in mind that we will need to have a base case that will stop the method when it finishes its work (going through the string and counting the vowels).

User Joebert
by
7.3k points

1 Answer

1 vote

Answer:

//Define the method as noOfVowels

//Let it receive the string to be checked as argument

public static int noOfVowels(String string){

//Check the length of the string

//If it is less than 1, then it is an empty string

//Hence return 0

if(string.length() < 1){

return 0;

}

//Else,

else{

//get the character at the first position in the string

//and convert it to a lower case

char x = string.toLowerCase().charAt(0);

//Check if the character is a vowel

if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'){

//if it is a vowel, add 1 to a recall of the method.

//But this time, call the method with

//the string excluding the first character.

//i.e the substring of the string starting at index 1 rather than 0

return 1 + noOfVowels(string.substring(1));

}

else {

//If it is not a vowel, just recall the method with

//the string excluding the first character

//i.e the substring of the string starting at index 1 rather than 0

return noOfVowels(string.substring(1));

}

}

}

Step-by-step explanation:

The code has been written in Java and it contains comments explaining every part of the code. Please go through the comments carefully.

The actual lines of code have been written in bold face to distinguish them from comments.

The code is re-written without comments as follows;

public static int noOfVowels(String string){

if(string.length() < 1){

return 0;

}

else{

char x = string.toLowerCase().charAt(0);

if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'){

return 1 + noOfVowels(string.substring(1));

}

else{

return noOfVowels(string.substring(1));

}

}

}

User Corashina
by
7.3k points