thedarkbutter thedarkbutter - 1 year ago 161
Java Question

Java palindrome checker - Case Insensitive

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.out.print("Enter one or more words: ");
String s =;

//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!

Answer Source

Use console.nextLine() instead of

By default, only gathers the next space-separated token, so when you enter "Os SO" it's only actually storing "Os" into the String s variable.

In terms of checking for palindromes, it is much easier to reverse the string and check if the reversed string is equal to the original instead of using indexes to check each individual character in the string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download