Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Answer in Java e. Write a recursive static method named makePalindrome that acce

ID: 3685599 • Letter: A

Question

Answer in Java

e. Write a recursive static method named makePalindrome that accepts a string and returns a palindrome of that string. For example, makePalindrome( “abc” ) returns “abccba”. You may use the substring function (i.e. you don’t have to use a helper).

Test the method with this code:

System.out.println("Test 4a: makePalindrome(): " + makePalindrome("a"));

System.out.println("Test 4b: makePalindrome(): " + makePalindrome("ab"));

System.out.println("Test 4c: makePalindrome(): " + makePalindrome("abc"));

Explanation / Answer

StringPalindrome.java


public class StringPalindrome {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       java.util.Scanner in = new java.util.Scanner(System.in);
       System.out.println("Please enter the string ");
       String str = in.nextLine();
       boolean status = isPalindrome(str);
       if(status){
           System.out.println("Given string is a palindrome");
       }
       else{
           System.out.println("Given string is not a palindrome");
       }
   }
   public static boolean isPalindrome(String str){
       // if length is 0 or 1 then String is palindrome
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length()-1))
/* check for first and last char of String:
* if they are same then do the same thing for a substring
* with first and last char removed. and carry on this
* until you string completes or condition fails
* Function calling itself: Recursion
*/
return isPalindrome(str.substring(1, str.length()-1));

/* If program control reaches to this statement it means
* the String is not palindrome hence return false.
*/
return false;
   }
}

Output:

Please enter the string
abc
Given string is not a palindrome

Please enter the string
abccba
Given string is a palindrome

Please enter the string
a
Given string is a palindrome

Please enter the string
ab
Given string is not a palindrome

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote