You are to write a program named Pallndreme.java that recognizes a Palindrome. I
ID: 3856963 • Letter: Y
Question
You are to write a program named Pallndreme.java that recognizes a Palindrome. In the main method complete the code to read a string from the user. Then call isPalindrome method to determine whether the entered string is a palindrome or not and display an appropriate message. You program must allow the user to repeatedly enter strings. Complete the isPalindrome method so that it returns true if the string is a and false if it isn't You must use a stack in your solution. You must use the Java API class java.util.Stack in your coding.Explanation / Answer
One way to check whether a string is palindrome or not, is to check whether the reverse of the string and the string itself are equal. Based on that logic the code using stack is given below.
Code:
import java.util.*;
class Test
{
void isPalindrome(String s){ //string s passed from procedure call in main method
Stack<Character> stack = new Stack<Character>(); //Creation of stack
String reverse="";
for(int i=0;i<s.length();i++) {
stack.push(s.charAt(i)); //push method adds a character in the stack
}
//Finding the reverse of the string
while (!stack.isEmpty()) {
reverse=reverse + stack.pop(); /*pop method returns the character present on top of the stack and removes it from stack */
}
if (s.equals(reverse)) //equals method checks whether s and reverse are same
System.out.println("Yes! that is a palindrome.");
else
System.out.println("No! that is not a palindrome.");
}//isPalindrome function ends
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
Test obj=new Test(); //object creation to call the method
for(int i=0; ;i++){ //runs infinitely
System.out.println("Input String: ");
String s=sc.next(); //input from user
s=s.toLowerCase(); //Convert to lower case to ignore the case
obj.isPalindrome(s); //Procedure call
System.out.println("Do you want to continue, 0.Exit 1.Continue");
int choice=sc.nextInt();
if(choice==0)
System.exit(0);
} //for loop ends
} //main function ends
} //class ends
Note:
The for loop runs infinite times. You need to enter '0' as a choice to break from it. Comments have been added to explain purposes wherever required.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.