Print long string palindrome in Java: error may be in removing white spaces & punctuation

Attempting to test for multiword palindromes such as “a man, a plan, a canal Panama”. I want to create a string to hold the lower case version of the input string, then create a result string to hold the letters – to be checked for a palindrome. Then loop through each character of the lower case string to determine if the character is a letter and if the character is a letter adding it to the result string.

This is my code:

import java.util.Scanner;

public class PalindromeCheck {

private static char resultString;

public static void main(String[] args) {

    Scanner input = new Scanner(;

    System.out.println("Enter a String: ");
    String s = input.nextLine();

    s = s.toLowerCase();
    String resultString = " ";

    for (int i = 0; i < s.length(); i++) {
        if (Character.isLetter(s.charAt(i)))
            resultString += s.charAt(i);

    int low = 0;
    int high = s.length() - 1;

    boolean isPalindrome = true;

    if (high >= 0)  {

    while (low < high) {
        if (s.charAt(low) != s.charAt(high)) {
            isPalindrome = false;
    else {
        isPalindrome = false;

    if (isPalindrome)
        System.out.println(s + " is a palindrome. ");
        System.out.println(s + " is not a palindrome. ");


When I run my code the white spaces and punctuations aren’t removed, so I have a feeling I’ve screwed something up in my first for loop- but I still can’t seem to figure it out. Inputing “a man, a plan, a canal Panama” results in “a man, a plan, a canal Panama is not a palindrome.”


Two things:

You are testing s, which hasn’t had punctuation removed yet, when resultString has had the punctuation removed. Add

s = resultString;

You initialize resultString to a space character " " which interferes with the palindrome testing. Initialize it to an empty string "" instead.

Leave a Reply

Your email address will not be published. Required fields are marked *