This Java program allows users to input a sentence and determines if it is a palindrom. All non-alphabetic characters including blanks, tabs, and punctuations are stripped from the sentence and the remaining characters are converted to Upper-Case for comparison of characters.
Implementation details:
// Palindrome P.C. 2004-11-07
//
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class test extends JFrame implements ActionListener{
private JTextArea notes;
private JTextField inField;
private JTextArea outArea;
private String out="";
public test(){
super("Palindrome");
// GUI stuff
notes=new JTextArea(5,20);
notes.setFont(new Font("Courier",Font.BOLD,11));
notes.append("Palindromes are words or sentences that\n");
notes.append("read forwards and backwards\n");
notes.append("For example: Ah, Satan sees Natasha\n");
notes.append("A Toyota! Race fast, safe car. A Toyota.\n");
notes.append("visit:http://www.palindromelist.com/ for more\n");
inField=new JTextField("Borrow or rob?",20);
inField.addActionListener(this);
outArea=new JTextArea(20,35);
outArea.setFont(new Font("Courier",Font.BOLD,11));
JScrollPane scr=new JScrollPane(outArea);
Container c=getContentPane();
c.setLayout(new FlowLayout());
c.add(notes);
c.add(inField);
c.add(scr);
this.setLocation(200,200);
setSize(350,500);
setVisible(true);
} // end constructor test
private boolean isPalindromeWord(String s){
// Check if given word s is a palindrom
int L=s.length();
for(int i=0;i<(int)(L/2);i++){
if(s.charAt(i)!=s.charAt(L-1-i))return false;
}
return true;
}
private boolean isPalindrome(String s){
// first strip s of all non-alphabetic characters
int ns=s.length();
char c[]=new char[ns]; int nc=0;
s=s.toUpperCase();
for(int i=0;i64 && c1<=90){c[nc]=c1; nc++;}
}
String s1=new String(c,0,nc); // s1 is now an upper-case alphabetic word
outArea.append(s1+"\n");
if(isPalindromeWord(s1))return true; else return false;
}
public void actionPerformed(ActionEvent event){
String txt=inField.getText();
String msg;
msg=(isPalindrome(txt))?"is a palindrom\n":"is NOT a palindrom\n";
outArea.append(msg);
}
} // end class test
public class Palindrome {
public static void main(String[] args){
test s=new test();
}
}