Why doesn’t my palindrome program work correctly? It always returns false, and I can’t tell why.
Here is my code:
public static boolean isPalindromIterative(String string) {
int a = 0;
int b = string.length() - 1;
while (b > a) {
if (a != b) {
return false;
}
a++;
b--;
}
return true;
}
Advertisement
Answer
You are comparing values of a and b which aren’t the same when you start comparing and hence you get false from your method.
In your if condition, Change it to be string.charAt(a) != string.chatAt(b)