I am currently trying to write a palindrome checker in Java that is case insensitive. I checked the other topics but none of them seems to solve my issue.
Here's my code:
import java.util.Scanner;
public class Homework5_2 {
public static void main(String[] args) {
boolean flag = true; //palindrome or not
Scanner console = new Scanner(System.in);
System.out.print("Enter one or more words: ");
String s = console.next();
//checks if string contains spaces
if (s.matches(".*\\s+.*")) {
s = s.replaceAll("\\s+","");
}
s = s.toLowerCase();
int stringLength = s.length();
int index = 0;
//checks the string from both sides going towards the middle
for (int i=0;i<stringLength/2;i++) {
index = stringLength-i-1;
if (!(s.charAt(i) == s.charAt(index))) {
flag = false;
}
}
if (flag == true) {
System.out.println("The string is a palindrome!");
} else {
System.out.println("The string is not a palindrome!");
}
}
}
When entering a string like "Os SO", the output in incorrect, as the string is not reported as a palindrome. The problem seems to be correlated with spaces, since the same string is correctly reported as a palindrome if there are no spaces in it. I'm really interested in understanding the flaw of this code, any help would be very much appreciated!