I need to create a palindrome tester program that ignores spaces, punctuation and uppercase/lowercase to determine if the string given to the user is a palindrome (same beginning to end as end to beginning).

HERE'S WHAT I HAVE SO FAR:

String str, another = "y";
        int left, right;

        Scanner scan = new Scanner(System.in);

        while(another.equalsIgnoreCase("y"))
        {
            System.out.println("Enter a potential palindrome: ");
            str = scan.nextLine();

            left = 0;
            right = str.length() - 1;

            while(str.charAt(left) == str.charAt(right) && left < right)
            {
                left++;
                right--;
            }

            System.out.println();

            if(left < right)
                System.out.println("That string is NOT a palindrome.");
            else 
                System.out.println("That string IS a palindrome.");

            System.out.println( );
            System.out.print("Test another palindrome (y/n)? ");
            another = scan.nextLine();
        }
    }   

Recommended Answers

All 3 Replies

You need to either upcase or downcase the input string before you test for palindrome. You could simply use toLowerCase() or toUpperCase() method to make all characters in the string to be either all lower or upper case.

//i.e.
str = scan.nextLine();
str = str.toLowerCase();

Line 22, left<right should be left<=right. If someone entered "aba" then the string should be palindrome.

You wanted to ignore spaces hence this peace of code to remove unwanted spaces from input string
str=str.replaceAll("\\s+", "");

@subramanya.vl

babi.meloo is obviously a beginner. Do you seriously think that they will understand how "\\s+" works? All they could do is copy/paste it like some Harry Potter spell and hope it works. Teach, explain.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.