Palindrome.java

Download Palindrome.java

 1: // This application checks the command line arguments to see if they
 2: // form a palindrome: text that reads the same forward or backward.
 3: // When checking, spaces and punctuation marks are ignored, and so
 4: // is the case of the text.  Examples include "Never odd or even."
 5: // and "Don't nod!".
 6: //
 7: // Written 11/2010 by Wayne Pollock, Tampa Florida USA
 8: 
 9: class Palindrome
10: {
11:    public static void main ( String [] args )
12:    {
13:       StringBuilder sb = new StringBuilder();
14:       for ( String word : args )
15:          sb.append( word );
16: 
17:       // Strip out non text, and convert case:
18:       String text = sb.toString().toUpperCase();
19:       text = text.replaceAll( "[^A-Z0-9]*", "" );
20: 
21:       System.out.println( isPalindrome( text ) );
22: 
23:    }
24: 
25:    // This is a recursive method:
26:    private static boolean isPalindrome ( String text )
27:    {
28:       int len = text.length();
29:       // no or 1 letter text is a palindrome:
30:       if ( len <= 1 )
31:          return true;
32: 
33:       // check if first character equals the last:
34:       if ( text.charAt(0) != text.charAt(len-1) )
35:          return false;  // not a palindrome!
36: 
37:       // If first == last, then check the middle:
38:       return isPalindrome( text.substring(1,len-1) );
39:    }
40: }