views:

2107

answers:

3

I have the program made up until the point where it has to ignore and punctuations and spaces in the thread and I was wondering if anyone could help me with the coding for that? What I've been trying out doesn't seem to be working. Here is what I have so far:

import java.util.Scanner;

public class PalindromeTester
{
public static void main (String[] args)

{

    String str, another = "y";

    int left, right;

    char charLeft, charRight;


    Scanner scan = new Scanner (System.in);


    while (another.equalsIgnoreCase("y")) // allows y or Y

    {

     System.out.println ("Enter a potential palindrome: ");

     str = scan.nextLine();

     left = 0;

     right = str.length() - 1;


     while (left < right)
     {
      charLeft = str.charAt(left);
      charRight = str.charAt(right);


      if (charLeft == charRight)
      {
       left++;
       right--;
      }

      else if (charLeft == ',' || charLeft == '.' ||
 charLeft == '-' || charLeft == ':' ||
 charLeft == ';' || charLeft == ' ')

       left++;

      else if (charRight == ',' || charRight == '.' ||
 charRight == '-' || charRight == ':' ||
 charRight == ';' || charRight == ' ')
       right--;
      else

       break;

     }

    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();
    }

 }

}
+1  A: 

You could simplify the code significantly by removing all the spaces and punctuation before you start. Look at String.replaceAll(regex,replacement). You would write a regular expression to match blanks and punctuation, and provide an empty string ("") as the replacement. This will return a new string containing the original minus the characters you want to ignore.

Jim Garrison
If what Ben Torrell suspects is true, regex's might be a wee above Lisa's head. You could accomplish the same thing with a bunch of calls to String.replace().
Chris Thompson
Or she could determine whether or not a character is a letter or not with Character.isLetter(char).
Ben Torell
+1  A: 

Look at char's documentation entry. Specifically the isLetterOrDigit method. If that method returns false, then it's punctuation or a space. There are other methods in there as well that can help with that.

nasufara
A: 

Just to clarify what Jim Garrison said, the regex you need is the following

String m = "Madam, I'm'',.,.''   Adam";
m = m.toLowerCase().replaceAll("\\W", "");

This will leave only letters and digits and remove whitespace and punctuation, i.e. m will become "madamimadam" and you can run you regular palindrome test on that string.

You can learn more about regular expressions here

tulskiy