A program that checks a string to see if the letters in the string read the same
ID: 3531563 • Letter: A
Question
A program that checks a string to see if the letters in the string read the same forward and backward. Theses 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 that the words read the same forward and backwards. For example "You can cage a swallow, can't you, but you can't swallow a cage, can you?" is a word-by-word palindrome. Write a program to test an input string and tell whether or not it is a word-by word palindrome. Consider upper- and lowercase letters to be the same letter. 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. Your program should have a friendly user interface and allow the user to check more lines until the user says he or she wishes to quit the program, this should be done using stacks and queues
Explanation / Answer
//do not use ',' or' ?' after the word otherwise the program will not work
import java.util.Scanner;
import java.util.Stack;
public class palindrome {
public static void main(String[] args)
{
String str;
boolean isPalindrome;
String words[]=new String[50];
Stack<String> stack=new Stack();
int choice;
Scanner input= new Scanner(System.in);
System.out.println("Enter the string");
str=input.nextLine();
isPalindrome=true;
words=str.split(" ");
int index;
for(int i=0;i<words.length;i++)
{
stack.push(words[i]);
}
for(int i=0;i<words.length;i++)
{
if(!words[i].equalsIgnoreCase(stack.pop()))
isPalindrome=false;
}
if(isPalindrome)
System.out.println("String is word by word palindrome");
else
System.out.println("String is not word by word palindrome");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.