153k views
4 votes
Write a recusrive method (no loops), called moreAs, which takes a String in JAVA. This method should add in 2 more a's every time an a is found in the String.

Sample Input 1: catalogue Sample Output 1: caaataaalouge
Sample Input 2: anagram Sample Output 2 :aaanaaagraaam

1 Answer

3 votes

Final answer:

To write a recursive method in Java that adds 2 more 'a's every time an 'a' is found in a given string, you can create a method called 'moreAs'. The method checks if the string is empty, if the first character is 'a', and recursively concatenates the appropriate string. An example implementation is provided.

Step-by-step explanation:

To write a recursive method in Java that adds 2 more 'a's every time an 'a' is found in a given string, you can follow the following steps:

  1. Create a method called 'moreAs' that takes a string as input.
  2. Check if the input string is empty. If so, return an empty string.
  3. Check if the first character of the string is 'a'. If so, concatenate 'aa' with the rest of the string and make a recursive call to 'moreAs' with the modified string as input.
  4. If the first character is not 'a', concatenate it with the recursive call to 'moreAs' with the rest of the string as input.

Here is an example implementation:

public class MoreAs {

public static String moreAs(String input) {
if (input.isEmpty()) {
return "";
}
if (input.charAt(0) == 'a') {
return "aa" + moreAs(input.substring(1));
}
return input.charAt(0) + moreAs(input.substring(1));
}

public static void main(String[] args) {
String input1 = "catalogue";
String input2 = "anagram";
System.out.println(moreAs(input1)); // Output: caaataaalouge
System.out.println(moreAs(input2)); // Output: aaanaaagraaam
}

}
User Fupsduck
by
7.0k points