Palindrome is a popular title for programming training. You may compare a pair of chars in a string, or a pair of words in a String array. Many homeworks are made in this way.
Further more, in Java we may play with all the speaking languages in the world, such as Chinese, Korean, Japanese, Russian, and so on since Java uses Unicode for its char type. I have written a simple program to show the usefulness of both the Java char and the StringBuffer which provides a reverse() method to reverse any string. Please check my code and provide comments.

import java.io.*;
import javax.swing.JOptionPane;
 public class Palindrome{   


 static boolean palindromeCouplet (String s)   {
 	StringBuffer s1 = new StringBuffer(s);
 return ((s.compareTo(new String(s1.reverse()))==0) ? true :false)  ;
 	}	

 public static void main(String[] args) {	
 	while(true){
    String str=JOptionPane.showInputDialog( null,  
	"Type in a word!\nPress cancel to ternimate。",
	"IS A PALINROME",
	JOptionPane.QUESTION_MESSAGE);    
    
	if (str == null) {
	System.out.println("Bey for now");
    	break;
    	} 
JOptionPane.showMessageDialog( null,  
	"Palindrome: " + palindromeCouplet(str),
	str + " IS A PALIDROME? ",
	JOptionPane.INFORMATION_MESSAGE);  
          }
      }   
}

Recommended Answers

All 2 Replies

Using the reverse method sort of defeats the purpose of the exercise, doesn't it? Unless all you want to do with java is call ready-made methods in the built-in classes, I suppose.

jon, thank you for your quick response. You are right for the sake of exercise. For the purpose of exercise we should write our own code as much as possible. But after we made extensive exercises we should definitely know if there is a ready-made method in Java so that in the future, when working in software industry, we may simply use the ready-made methods instead of our-own made if the code we made is not better than the ready-made.

One question for students:
Why class String has no reverse() method?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.