Search code examples
javapalindrome

Palindrome checker - spacing


I have a program where I am typing a Java program to check if the String entered is a palindrome. I have 2 problems going on that I can not for the life of me seem to figure out.

I have typed out the code so that it will tell me if it is a palindrome when all lowercase letters and no spaces involved. Any time I enter a palindrome with a space anywhere in it, it will tell me it is not a palindrome. Think I am just missing one little piece of code to make it work.

import java.util.Scanner;

public class HW3 {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        String word;
        String backwards = "";

        System.out.println("Enter a word or phrase and I'll tell you if it's a palindrome");
        word = keyboard.nextLine();

        int length = word.length();

        for (int i = length - 1; i >= 0; i--) {
            backwards = backwards + word.charAt(i);
        }

        if (word.equalsIgnoreCase(backwards)) {
            System.out.println(word + " is a palindrome!");
        }
        else {
            System.out.println("That is not a palindrome!");
            System.exit(0);
        }

        System.out.println("Done!");
    }
}

Solution

  • Your program works as expected. (At least how I expect it to work; "taco cat" does not equal "tac ocat" so it should not be regarded as a palintrome.)

    If you want to disregard from spaces, you could do

    word = word.replaceAll("\\s", "");
    

    right after reading the input string.