Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Palindrome program

807598Jan 22 2006 — edited Mar 19 2009
I'm trying to write a program that tells you whether a String is a palindrome, or not an almost palindrome. Almost Palindromes are palindromes once you remove the spaces and punctuations. If you only look at the letters or numbers you will see a Palindrome. Examples of AlmostPalindromes are:

Madam, I'm adam
A MAN, A PLAN, A CANAL, PANAMA

But, on the code I'm working on, it displays the opposite of whatever I want it to.


 import java.io.*;

public class lab16b
{

public static void main (String args[]) throws IOException
	{   
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
		boolean finished = false;

		do
		{
			System.out.print("Enter a string  ===>>  ");
			Palindrome p = new Palindrome(input.readLine());        
			
			p.displayData();
			System.out.print("\nDo you wish to repeat this program [Y/N]?  ===>>  ");
			String repeat=input.readLine();
      		boolean right=(repeat.equals("Y") || repeat.equals("yes")||repeat.equals("y")||repeat.equals("YES"));
      		if (right)
			{
			
  			 System.out.println(); 
			}
			else 
			{
			System.out.println();
   			finished = true;
			}
		}
		while (!finished); 	
}
}

class Palindrome
{
   private String s1;		// stores original string entered at the keyboard
   private String s2;		// stores s1 with punctuation and spaces removed
   private boolean palindrome;
   private boolean almostPalindrome;

  
   private boolean isPal(String s)
   {
   	s1=s1.toLowerCase();			
   
   	int a=0;
    int b=s1.length()-1;
 
    while (a<b)
    {
      if(s1.charAt(a) != s1.charAt(b))
      {
   
        return false;
      }
      a++;
      b--;
    }
   
    return true; 		
  }

   	

   private boolean isAlmostPal()
   {
   	s1=s2;
   	s2=s2.toLowerCase();		
    s2=s2.replaceAll("[^a-zA-Z]+", "");	
    
    int a=0;
    int b=s2.length()-1;
 
    while (a<b)
    {
      if(s2.charAt(a) != s2.charAt(b))
      {
   		
        return false;
      }
      a++;
      b--;
    }
   		

   return true; 
  }
   
  


   public Palindrome(String s)
   {
   	s1=s;
   	s2="";
   }

   public void displayData()
   {
   	 if (isPal(s1))
  	 {
      System.out.println("Palindrome: true");
    }
    else
    {
    
      System.out.println("Palindrome: false");
    }
    
    if(isAlmostPal())
     {
      System.out.println("Almost Palindrome: true");
    }
    else
    {
    
      System.out.println("Palindrome: false");
    }
  }

}
Could somebody please tell me what I am doing wrong?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 16 2009
Added on Jan 22 2006
27 comments
964 views