Fill in the method template below to make a working method. Make sure your metho
ID: 3772566 • Letter: F
Question
Fill in the method template below to make a working method. Make sure your method conforms to the instructions given in the comments for the method.
public static boolean Vowels(String str ){
/* Write a recursive method called Vowels that takes a String as an argument and returns true if the String contains any 'a', 'e', 'i', 'o', or 'u' characters, false if it does not contain any one of these characters. Identify your base case and your general case. You may assume that the input String will never be allowed to be null. FULL CREDIT WILL ONLY BE AWARDED FOR A RECURSIVE SOLUTION */
Explanation / Answer
The following is the requried recursive method:
//recursive method, which returns true,
//if string contains at least a vowel
public static boolean Vowels(String str)
{
//base case(stop when sting is empty. That is, when the length is zero)
if(str.length()==0)
{
return false;
}
//general case( if a vowel is encountered , return true.
//otherwise call the function recursively
if(str.charAt(0)=='a' ||str.charAt(0)=='e'||str.charAt(0)=='i'||str.charAt(0)=='o'||str.charAt(0)=='u')
{
return true;
}
else
{
//recursive call
return Vowels(str.substring(1,str.length()));
}
}
Complete program:
Sample output:
Code to copy:
import java.util.Scanner;
public class RecursionDemo
{
public static void main(String arg[])
{
String str;
Scanner input =new Scanner(System.in);
System.out.println("Enter a string: ");
str=input.next();
if(Vowels(str))
System.out.println("Vowels exist in the given string");
else
System.out.println("No vowels exist in the given string");
}
//recursive function , which returns true,
//if string contains at least a vowel
public static boolean Vowels(String str)
{
//base case(stop when sting is empty. That is, when the length is zero)
if(str.length()==0)
{
return false;
}
//general case( if a vowel is encountered , return true.
//otherwise call the function recursively
if(str.charAt(0)=='a' ||str.charAt(0)=='e'||str.charAt(0)=='i'||str.charAt(0)=='o'||str.charAt(0)=='u')
{
return true;
}
else
{
//recursive call
return Vowels(str.substring(1,str.length()));
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.