Write a program to determine whether an input string is a palindrome. You are to
ID: 3756482 • Letter: W
Question
Write a program to determine whether an input string is a palindrome. You are to use a stack .
Output should be of the form
"A Toyota's a Toyota." is a palindrome. (Note the apostrophe and the period)
To earn full points:
Create a method that inputs a string and returns that string (all the same case and no punctuation).
Create a method called isPalin, which returns true or false depending on whether the argument is a palindrome or not.
Your main program will then output either "is a palindrome" or "is not a palindrome" depending what is returned from the method.
isPalin, MUST use a stack
Explanation / Answer
import java.util.*;
import java.io.*;
public class Palindrome
{
public static String getString()
{
try{
FileReader fr = new FileReader("palin.txt");
// create a Scanner object
Scanner sc = new Scanner(fr);
// read complete line
String str = sc.nextLine();
return str;
}
catch(Exception e)
{
e.printStackTrace();
}
return "";
}
public static boolean isPalin(String str)
{
int i, size = 0;
// create a Stack object which stores characters
Stack<Character> stk1 = new Stack<Character>();
// create a Stack object which stores characters
Stack<Character> stk2 = new Stack<Character>();
for( i = 0 ; i < str.length() ; i++ )
{
// check if the current character is letter
if(Character.isLetter(str.charAt(i)) == true)
{
// push element into stack
stk1.push(str.charAt(i));
size++;
}
}
for( i = 0 ; i < size / 2 ; i++ )
{
// pop the top element from first stack
char ch = stk1.pop();
// push the popped element into second stack
stk2.push(ch);
}
// if the number of elements in stack were odd
// remove the top most element from first stack
if(size % 2 != 0)
stk1.pop();
// false if String is not palindrome
// true if String is palindrome
boolean flag = true;
// loop untill the stack is empty
while(!stk1.empty())
{
// pop element from first stack
char ch1 = stk1.pop();
// pop element from second stack
char ch2 = stk2.pop();
// if the characters don't match
if(ch1 != ch2)
{
flag = false;
break;
}
}
return flag;
}
public static void main(String[] args)
{
// get string from file
String temp = getString();
// convert STring to lower case
String str = temp.toLowerCase();
boolean flag = isPalin(str);
if(flag == true)
System.out.println(" It is a Palindrome.");
else
System.out.println(" It is not a Palindrome.");
}
}
-------------------------palin.txt-------------------------
A Toyota's a Toyota.
Sample Output
It is a Palindrome.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.