In Figure 73 on page 367 of the required text book we presen
In Figure 7.3 on page 367 of the required text book, we presented a program that checks a string to see if the letters in the string read the same forward and backward. These strings are called palindromes. Another kind of palindrome is one in which we look at words rather than letters. A word-by-word palindrome is a string of words such hat the words read the same forward and backward. For example, the quote \"You can cage a swallow, can\'t you, but you can\'t swallow a cage, can you?\" is a word-by-word palindrome.
**JAVA** Write a method named isWordPalindrome in a class named PalindromeChecker with the following signature for the method.
public boolean isWordPalindrome(String input) { \\* *\\ }
Consider upper- and lower-case letters to be the same letters. Define a word as any string consisting of only letters or an apostrophe and bounded at each end with one of the following: a space, a punctuation mark, the beginning of the line, or the end of the line.
Solution
// PalindromeChecker.java
import java.util.Scanner;
public class PalindromeChecker
{
public static boolean isWordPalindrome(String input)
{
input = input.replaceAll(\"[-+.^:,?]\",\"\");
input = input.toLowerCase();
if (input == null)
{
return false;
}
String[] substrings = input.split(\" \");
int length = substrings.length;
for (int i = 0; i < length/2; i++)
{
if (!substrings[i].equals(substrings[length - 1 -i]))
{
return false;
}
}
return true;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
char again = \'y\';
while(true)
{
System.out.println(\"Enter text: \");
String s = sc.nextLine();
if(isWordPalindrome(s) == true)
System.out.println(\"YES, the inout text is a Palindrome!\");
else
System.out.println(\"NO, the inout text is not a Palindrome!\");
System.out.println(\"\ Would you like to test another string (y/n)? \");
again = sc.next().charAt(0);
if(again == \'n\' || again == \'N\')
break;
sc.nextLine(); // Consume newline left-over
}
}
}
/*
output:
Enter text:
You can cage a swallow, can\'t you, but you can\'t swallow a cage, can you?
YES, the inout text is a Palindrome!
Would you like to test another string (y/n)?
y
Enter text:
my name is ayush verma ayush is name my
YES, the inout text is a Palindrome!
Would you like to test another string (y/n)?
y
Enter text:
my class is 111th but 111th is not class my
NO, the inout text is not a Palindrome!
Would you like to test another string (y/n)?
n
*/

