JAVA A palindrome is a word or group of words that reads the same forward as bac
ID: 3692192 • Letter: J
Question
JAVA
A palindrome is a word or group of words that reads the same forward as backward. Examples of palindromes are: radar, noon, and "Madam, I'm Adam". Notice there are different scenarios in the examples: In the palindrome 'radar' the letters on either side of the 'd' are the same. In the palindrome 'noon' the first half of the word ('no') is the mirror image of the second half ('on') of the word. In the palindrome "Madam, I'm Adam" the punctuation is ignored. Create a program which utilizes Queues to determine if a string is a palindrome. In trying to determine if a string is a palindrome, ignore punctuation. When determining if a string is indeed a palindrome, you will want to compare a reversed version of the string to itself. Recall that we used Stacks to create a reversed version of a string. Do the following: Read each string from an external file, converts each character within the string to lower case, and place each character on a Queue and on a Stack. Using both the Queue and the Stack, have the program verify whether or not the string is a palindrome. Be sure to ignore all white space and punctuation (commas, apostrophes, periods, etc.). Use Object Oriented programming and ADT structures. Use the following strings in your external file: A daffodil slid off Ada A Toyota's a Toyota Never odd or even This one is not a palindrome Did Hannah say as Hannah did A man, a plan, a canal -- Panama Was it a car or a cat I saw?Explanation / Answer
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.io.*;
public class Palindrometest
{
public static void main(String[] args) throws IOException
{
Scanner stdin = new Scanner(System.in);
//Scanner stdin = new Scanner(new File("input.txt"));
String line;
do
{
System.out.print("Your expression (or return to end): ");
line = stdin.nextLine();
if (is_palindrome(line))
System.out.println("that is a palindrome");
JOptionPane.showMessageDialog(frame, "That is a palindrome");
else
JOptionPane.showMessageDialog(frame, "That is NOT a palinfrome");
System.out.println("that is NOT a palindrome");
}
while (line.length() != 0);
}
public static boolean is_palindrome(String input)
{
Queue<Character> q = new LinkedList<Character>();
Stack<Character> s = new Stack<Character>();
Character letter;
int mismatches = 0;
for (int i = 0; i < input.length(); i++)
{
letter = input.charAt(i);
if (Character.isLetter(letter))
{
q.add(letter);
s.push(letter);
}
}
while (!q.isEmpty())
{
if (q.remove() != s.pop())
mismatches++;
}
return (mismatches == 0);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.