In: Computer Science
1) Only a single main class is required
2) The main class must contain a static method called "getInputWord" that prompts a user to input a word from the keyboard and returns that word as a String. This method must use "JOptionPane.showInputDialog" to get the input from the user (you can find info about JOptionPane in JavaDocs)
3) The main class must contain a static method called "palindromeCheck" that takes a String as an input argument and returns a boolean indicating whether or not that String is a palindrome. This method must utilize a Stack data structure to determine whether the word is a palindrome. Hint: Use the charAt() method of the String class to access each character of the word
Flow of the Program:
1) Read in a word from the user by calling the "getInputWord" method
2) Check if the word is a palindrome using the "palindromeCheck" method
3) Output the result to the screen using "JOptionPane.showMessageDialog" (you can find info about JOptionPane in JavaDocs)
import java.util.Stack;
import javax.swing.JOptionPane;
public class PalindromeCheckerUsingStack {
public static void main(String[] args) {
String input = getInputWord();
if(palindromeCheck(input)){
JOptionPane.showMessageDialog(null,"String is palindrome"); // show
message
}else{
JOptionPane.showMessageDialog(null,"String is not
palindrome");
}
}
public static boolean palindromeCheck(String input)
{
String palindromeString = ""; // to
append stack input
// initialize a stack
Stack<Character> stack = new Stack<Character>();
// iterate over the string
for (int i = 0; i <
input.length(); i++) {
char character = input.charAt(i);
stack.push(character);
}
// iterate over the stack till it is empty
while (!stack.isEmpty()) {
// add the character at the top to a string
palindromeString = palindromeString + stack.pop();
}
// compare original and reversed strings
if (input.equals(palindromeString))
{
return true;
} else {
return false;
}
}
private static String getInputWord() {
return JOptionPane.showInputDialog("Please Enter a word: "); //
reading a word
}
}
/* OUTPUT */
/* PLEASE UPVOTE *./