Create a class named Palindrome.java then implements the recursive method specif
ID: 3881902 • Letter: C
Question
Create a class named Palindrome.java then implements the recursive method specified below: public boolean isPalindrome(String s) The recursive method: isPalindrome takes a string as a parameter and that returns true if the string is a palindrome and false if it is not. A palindrome is a string like "racecar" that has the same sequence of characters when written forwards and backwards. Notice that in a palindrome, the first and last characters match, as do the second and second-to-last, the third and third-to-last, and so on. However, when we test if a string is a palindrome, we only consider alphabetic letters(a-z and ignore cases) and digits (0-9), we simply ignore all other symbols. The table below includes various method calls and the value returned: Method Call Result ---------------------------------------------------------------------- isPalindrome("radar") true isPalindrome("Was It A Rat I Saw?") true isPalindrome("pe e p") true isPalindrome("x") true isPalindrome("12321") true isPalindrome("Java") false
Explanation / Answer
The program takes an input string "rac ecAR" to check whether it is a palindrome or not. "rac ecAR" is a palindrome as per the program requirement. The logic of the program is to remove all blank spaces and convert string into lowercase before comparing with the reversed one.
---------------------------------------------------------------------------------
class palCheck
{
boolean isPalindrome(String str)
{
String rev = "";
str=str.toLowerCase(); //convert the string to all lower case
str = str.replaceAll("\s", ""); //remove all whitespaces
int length = str.length(); //find the length of string
/* code to reverse the string and compare with original string */
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
if (str.equals(rev))
return(true);
else
return(false);
}
}
public class Palindrome
{
public static void main(String args[])
{
palCheck obj = new palCheck();
boolean x = obj.isPalindrome("rac ecAR");
if(x==true)
System.out.println(" is a palindrome");
else
System.out.println(" is not a palindrome");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.