2. A palindrome is a word or phrase that reads the same forward and backward, ig
ID: 3910173 • Letter: 2
Question
2. A palindrome is a word or phrase that reads the same forward and backward, ignoring blanks and considering uppercase and lowercase versions of the same letter to be equal. For example, the following are palindromes: • warts n straw radar • Able was I ere I saw Elba tacocat Write a program that will accept a sequence of characters terminated by a period and will decide whether the string- without the period-is a palindrome. You may assume that the input contains only letters and blanks and is at most 80 characters long. Include a loop that allows the user to check additional strings until she or he requests that the program end. (Hint: Define a static method called is Palindrome that begins as follows.) /** Precondition: The array a contains letters and blanks in positions a[0] through a[used - 1]. Returns true if the string is a palindrome and false otherwise. public static boolean is Palindrome(char[] a, int used) Your program should read the input characters into an array whose base type is char and then call the preceding method. The int variable used keeps track of how much of the array is used, as described in the section entitled "Partially Filled Arrays.Explanation / Answer
import java.util.Scanner;
public class PalindromeTest
{
public static void main(String[] args)
{
int used = 0;
char[] chars = new char[80];
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string characters, terminated by a period.");
String data,cq;
do
{
//input word from user.
data = scan.nextLine();
//loop to read each char in string into char array
for(int i=0;i<data.length();i++)
{
//storing chars into char array
chars[i]=data.charAt(i);
}
used=(data.length());
//check for palindrome.
if(isPalindrome(chars, used))
System.out.println(data + " is a palindrome.");
else
System.out.println(data + " is not a palindrome.");
//request to continue or quit.
System.out.println("Continue or Quit?");
cq = scan.nextLine();
}
while (cq.equalsIgnoreCase("continue"));
System.exit(0);
}
//return true if the word is a palindrome, otherwise returns false.
public static boolean isPalindrome(char[] a, int used)
{
int i = 0, j = used - 1;
while(i<j)
{
if(a[i] == a[j])
{
i++;
j--;
}
else
{
return false;
}
}
return true;
}
}
Output:
Enter a string characters, terminated by a period.straw n warts
straw n warts is a palindrome.
Continue or Quit?
Continue
apple
apple is not a palindrome.
Continue or Quit?
Continue
radar
radar is a palindrome.
Continue or Quit?
Continue
is a palindrome.
Continue or Quit?
Continue
madam
madam is a palindrome.
Continue or Quit?
Quit
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.