Hello (my first post), I should write a program that checks if a sentence or a word is a Palindrome. For this I must use Stacks. The thing is that I print both solutions out in the console but even if they are the same it returns false.
My Code:
public class Palindrome {
// Test if text is a palindrome.
// Ignore upper/lower case, white space, and punctuation.
//
public static boolean isPalindrome(String text) {
boolean ispalin =false;
char tmp;
String temp = text;
String text2 = "";
String check = "";
Stack<Character> stacktext = new Stack<Character>();
Stack<Character> stackcheck = new Stack<Character>();
text = text.toLowerCase();
for (int j = 0; j < text.length(); j++) {
if( text.charAt(j) != ' '&&
text.charAt(j) != ','&&
text.charAt(j) != '?'&&
text.charAt(j) != '.'&& //delete some symbols
text.charAt(j) != '!'&&
text.charAt(j) != '-'){
tmp = text.charAt(j);
text2 += tmp;
}
}
for (int j = text.length()-1; j > -1; j--) {
if( text.charAt(j) != ' '&&
text.charAt(j) != ','&&
text.charAt(j) != '?'&&
text.charAt(j) != '.'&&
text.charAt(j) != '!'&&
text.charAt(j) != '-'){
tmp = text.charAt(j);
check += tmp;
}
}
for (int i = 0; i < text2.length(); i++) {
stacktext.push(text2.charAt(i));
}
for (int i = check.length()-1; i != -1; i--) {
stackcheck.push(check.charAt(i));
}
System.out.println(stackcheck);
System.out.println(stacktext);
if (stackcheck == stacktext) return true;
else return false;
}
public static void main(String[] args) {
System.out.println(isPalindrome("Na, Fakir, Paprika-Fan?"));
}
}
The Output:
[n, a, f, a, k, i, r, p, a, p, r, i, k, a, f, a, n]
[n, a, f, a, k, i, r, p, a, p, r, i, k, a, f, a, n]
false