In: Computer Science
Write a Java program that prompts the user to input a string and prints whether it is a palindrome. A palindrome is a string which reads the same backward as forward, such as Madam (disregarding punctuation and the distinction between uppercase and lowercase letters). The program must use the stack data structure.
The program must include the following classes:
The StackX class (or you can use the Java Stack class).
The Palindrome class which must contain a method named palindrome()
of type boolean. The method must return true if the string is a
palindrome and false otherwise.
The Test class which must contain the main method. In the main
method, you must prompt the user to input a string and print “The
string is a palindrome” if the inputted string is a palindrome.
Otherwise, you must print “The string is not a palindrome.”
Here is a sample run:
Enter a word: Madam
The string is a palindrome
Here is another sample run:
Enter a word: Able was I, ere I saw Elba.
The string is a palindrome
Here is another sample run:
Enter a word: Data Structures.
The string is not a palindrome
======================================================================================
public class StackX {
private long [] stackArray ;
private int top ;
public StackX ( int size )
{
stackArray = new long [ size ]; // create the stack
top = -1; // set the top to -1
}
public void push ( long j ) {
stackArray [++ top ] = j ; // increment top , insert item
}
public long pop ()
{
return stackArray [ top - -]; // access item , decrement top
}
Program Code [JAVA]
import java.util.Scanner;
import java.util.Stack;
// Palindrome class
class Palindrome {
String word;
// Constructor
public Palindrome(String word) {
this.word = word;
}
// palindrome method
public boolean palindrome() {
// Return true if word is palindrome else false
// Java Stack class to Store characters & converting whole string to lowercase for case-insensitive match
Stack<Character> stack = new Stack<Character>();
word = word.toLowerCase();
// Pushing each character of word in StackX
for (int i=0; i<word.length(); i++)
stack.push(word.charAt(i));
// Now popping from stack and matching with each character - If any wrong match it is not palindrome
for (int i=0; i<word.length(); i++) {
if(stack.pop() != word.charAt(i))
return false;
}
return true;
}
}
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Asking user to input a string
System.out.print("Enter a word: ");
String word = input.nextLine();
Palindrome p = new Palindrome(word); // calling palindrome function
if(p.palindrome())
System.out.println("The string is a palindrome");
else
System.out.println("The string is not a palindrome");
}
}
Sample Output:-
----------------------------------------------------------------------
COMMENT DOWN FOR ANY QUERIES!!!
HIT A THUMBS UP IF YOU DO LIKE IT!!!