0

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!

2 Answers2

2

Use console.nextLine() instead of console.next().

By default, console.next() 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.

Matt Coats
  • 322
  • 1
  • 5
0

This is my solution for the problem:

import java.util.Scanner;

public class CheckPalindrome {

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        String userInput = "";
        String auxiliar = "";

        userInput = console.nextLine();
        auxiliar = new StringBuilder(userInput).reverse().toString();

        if (userInput.equalsIgnoreCase(auxiliar)) {
            System.out.println("This string is a palindrome");
        } else {
            System.out.println("This string is not a palindrome");
        }

        console.close();
    }
}