November 19, 2003
Testing for a Palindrome
Enter a sentence below to find out if it is a palindrome.
/*
Test to see if an input sentence is a palindrome
*/
import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class Palindrome extends Applet implements ActionListener { // GUI Variables Label enterLabel = new Label("Enter a sentence...", Label.LEFT); TextField enterField = new TextField(60); Button goButton = new Button("Is it a Palindrome?"); // Program variables String sentence; public void init() { makeGui(); } // init public void paint(Graphics g) { g.drawString("Sentence = "+sentence, 30, 30); sentence = process(sentence); // clean it up first! g.drawString("Sentence = "+sentence, 30, 50); // see if it is a palindrome if (isPalindrome(sentence)) g.drawString("It is a palindrome!", 30, 70); else g.drawString("It is not a palindrome.", 30, 70); } // paint public String process(String s) { String clean; // Convert all letters to lower case s = s.toLowerCase(); // Remove all punctuation clean = ""; for (int i=0; i < s.length(); i++) { if (isAlpha(s.charAt(i))) clean = clean + s.charAt(i); } return clean; } // process public boolean isAlpha(char c) { // retruns true if c is between 'a'..'z' return ((c >= 'a') && (c <= 'z')); }// isAlpha public boolean isPalindrome(String s) { // returns true is s is a palindrome, false otherwise int left = 0; int right = s.length() - 1; while( left < right ) { if (s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; } // isPalindrome public void actionPerformed(ActionEvent e) { // get the input sentence sentence = enterField.getText(); repaint(); } // actionPerformed private void makeGui() { // create 3x1 panel Panel p = new Panel(); p.setLayout(new GridLayout(3,1)); // Draw the label p.add(enterLabel); // Draw the text field Panel tPanel = new Panel(); tPanel.add(enterField); p.add(tPanel); // Draw the button Panel bPanel = new Panel(); bPanel.add(goButton); p.add(bPanel); p.setBackground(Color.cyan); // applet layout this.setLayout(new BorderLayout()); this.add(p, "South"); this.setBackground(Color.yellow); // Register listener for button goButton.addActionListener(this); } // makeGui } // Palindrome