In: Computer Science
A palindrome is a word or phrase, which reads the same backward or forward. Write a program that prompts the user for a string of characters terminated by a period and determines whether the string (without the period) is a palindrome.
IMP:
Assume that the input contains only letters and blanks.
Assume also that the input is at most 30 characters long. Use an
array of characters of size 30 to store the input!
Disregard blanks when deciding if the string is a palindrome and
consider upper case and lower-case version of the same letter to be
equivalent.
Provide a static method
palindrome public static boolean palindrome(char[] a, int
number)
that accepts a char array containing the characters of the input
string, and an integer defining the number of characters in the
string.
Your program should test the palindrome method by calling it on the
input entered by the prompted user and converted to an array.
Please add comments so I understand this problem.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PalindromeArray { public static boolean isPalindrome(char[] a, int used) { int left = 0, right = used - 1; while (left < right) { if(!Character.isAlphabetic(a[left])) { // if left character is not an alphabet then advance to next character left++; } else if(!Character.isAlphabetic(a[right])) {// if right character is not an alphabet then advance to previous character right--; } else { // if characters from both ends are alphabets then check if they are equal if(Character.toLowerCase(a[left]) != Character.toLowerCase(a[right])) { return false; } left++; // increase left by 1 right--;// decrease right by 1 } } return true; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter String: "); char[] data = new char[80]; int len = 0; char ch; while((ch = (char) br.read()) != '.') { data[len++] = ch; } System.out.println(isPalindrome(data, len)); } }