/* COSC 304 section 2 LUKE BURGESS luke_burgess@hotmail.com @00205854 Oct 13 2000 */ // Lab task: Chapter 7, Exercise 7.30, page 314 from "Java How To Program", Deitel & Deitel // Removes spaces and punctuation (if any) from given word(s) and // tests to see if result is a palindrome. import javax.swing.JApplet; import javax.swing.JOptionPane; import javax.swing.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class Exercise30p314 extends JApplet implements ActionListener { private JLabel inputLabel, outputLabel; private JTextField inputField; private JTextArea output; public void init () { Container c = getContentPane(); c.setLayout (new FlowLayout()); c.setBackground(Color.decode("#ccccff")); inputLabel = new JLabel ("Enter text:"); inputField = new JTextField (20); inputField.addActionListener (this); c.add (inputLabel); c.add (inputField); outputLabel = new JLabel (" Answer:"); output = new JTextArea (1, 20); output.setBackground(Color.decode("#ccccff")); c.add (outputLabel); c.add (output); } // init() public void actionPerformed (ActionEvent e) { String s = e.getActionCommand().toString(); if (testPalindrome (s)) output.setText ("Is a palindrome"); else output.setText ("Is not a palindrome"); } // actionPerformed() public static boolean testPalindrome (String s) { String stripped = stripInvalidChars (s); int firstIndex = 0; int lastIndex = stripped.length() - 1; char firstValidChar; char lastValidChar; boolean answer; if (stripped.length() < 2) answer = true; else { firstValidChar = Character.toLowerCase (stripped.charAt (firstIndex)); lastValidChar = Character.toLowerCase (stripped.charAt (lastIndex)); if (firstValidChar != lastValidChar) answer = false; else // Test all other characters answer = testPalindrome (stripped.substring (firstIndex + 1, lastIndex)); } // else return answer; } // testPalindrome() // Invalid characters include punctuation and spaces. public static String stripInvalidChars (String s) { int first = 0; int last = s.length() - 1; boolean validFirst; boolean validLast; boolean done = false; // Increment first and decrement last until each indexes a valid // character, or there are no valid characters to be found. while ((first < last) && !done) { validFirst = Character.isLetterOrDigit (s.charAt (first)); validLast = Character.isLetterOrDigit (s.charAt (last)); if (validFirst && validLast) done = true; else { if (!validFirst) first ++; if (!validLast) last --; } // else } // while() if (first <= last) return s.substring (first, last + 1); else return ""; } // stripInvalidChars() } // class Exercise30p314