The code littered with System.out.println is messy and hard to read.
Always try to decompose your code to smaller units (methods, classes)
that each have a single responsibility.
Using StringBuilder.reverse as @Legato@Legato did is clever,
but it probably defeats the purpose of the exercise.
Here's another implementation that's still simple enough and doesn't cheat.
private boolean isPalindrome(String string) {
String text = string.replaceAll("\\W+", "").toLowerCase();
int len = text.length();
for (int i = 0; i < len / 2; ++i) {
if (text.charAt(i) != text.charAt(len - 1 - i)) {
return false;
}
}
return true;
}
Particularly bad elements in your implementation:
- Excessive use of print statements (actually there shouldn't be any)
- Multiple
.toLowerCaseand.equalsIgnoreCasecalls, when you could do.toLowerCaseonce at the very beginning, and then simply use.equalseverywhere - Since whitespace characters are also non-word characters,
.replaceAll("\\s+", "").replaceAll("\\W+", "")can be simplified to.replaceAll("\\W+", "")