1 public class Palindromes
2 {
3 public static void main(String[] args)
4 {
5 String sentence1 = "Madam, I'm Adam!";
6 System.out.println(sentence1);
7 System.out.println("Palindrome: " + isPalindrome(sentence1));
8 String sentence2 = "Sir, I'm Eve!";
9 System.out.println(sentence2);
10 System.out.println("Palindrome: " + isPalindrome(sentence2));
11 }
12
13 /**
14 Tests whether a text is a palindrome.
15 @param text a string that is being checked
16 @return true if text is a palindrome, false otherwise
17 */
18 public static boolean isPalindrome(String text)
19 {
20 int length = text.length();
21
22 // Separate case for shortest strings.
23 if (length <= 1) { return true; }
24 else
25 {
26 // Get first and last characters, converted to lowercase.
27 char first = Character.toLowerCase(text.charAt(0));
28 char last = Character.toLowerCase(text.charAt(length - 1));
29
30 if (Character.isLetter(first) && Character.isLetter(last))
31 {
32 // Both are letters.
33 if (first == last)
34 {
35 // Remove both first and last character.
36 String shorter = text.substring(1, length - 1);
37 return isPalindrome(shorter);
38 }
39 else
40 {
41 return false;
42 }
43 }
44 else if (!Character.isLetter(last))
45 {
46 // Remove last character.
47 String shorter = text.substring(0, length - 1);
48 return isPalindrome(shorter);
49 }
50 else
51 {
52 // Remove first character.
53 String shorter = text.substring(1);
54 return isPalindrome(shorter);
55 }
56 }
57 }
58 }