PLEASE HELP IN JAVA: Write a program to determine whether an input string is a p
ID: 3889256 • Letter: P
Question
PLEASE HELP IN JAVA:
Write a program to determine whether an input string is a palindrome. You are to use a stack .
Input file is p.txt Each phrase is on a line in the input file. (Must use try/catch). Output should be of the form: "A Toyota's a Toyota." is a palindrome.
Create a method called isPalin, which returns true or false depending on whether the argument is a palindrome or not. Your main program will call this method with the input string as the argument, and then output either "is a palindrome" or "is not a palindrome" depending what is returned from the method.
isPalin, MUST use a stack.
p.txt:
I man am regal
a German
am i
Never
odd
or even
lever
Rats
live
on an evil
star
If I had a Hi-Fi
racecard
Too
hot to hoot
Do geese
see
God?
Explanation / Answer
Java Program:
import java.util.*;
class TestStringPalindromeSTACK
{
//Main method
public static void main(String[] args)
{
//Creating a scanner class object
Scanner reader = new Scanner(System.in);
//Creating a Stack class object
Stack<Character> stackObj = new Stack<Character>();
String ipString, revString = "";
//Reading a string
System.out.print(" Input a string: ");
ipString = reader.nextLine();
//Iterating over each character in the string
for (int i = 0; i < ipString.length(); i++)
{
//Pushing character into stack
stackObj.push(ipString.charAt(i));
}
//Iterating over stack until it is empty
while (!stackObj.isEmpty())
{
//Constructing a reverse string
revString += stackObj.pop();
}
//Comparing strings
if (ipString.equalsIgnoreCase(revString))
{
//Both strings are same
System.out.println(" String " + ipString + " is a palindrome. ");
}
else
{
//Both strings are not same
System.out.println(" String " + ipString + " is not a palindrome. ");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.