Page 427 - Computer science 868 Class 12
P. 427

2.  A class called Palword is defined to check if a word is a palindrome or not.
                        A palindrome is a word which reads same from both ends e.g., NOON, MADAM, MALAYALAM etc. The details of the class is given
                       below.
                        Data Members
                        String w                                 :  To store any word
                        String rw                                :  To store the reverse string
                        Member Methods
                        void read()                              :  Accepts any word in upper case
                        String revword(String x)                 :  Using recursive technique, returns the reverse of the word
                        void check()                             :  Calls revword (String) and prints if w is a palindrome or not
                        static void main()                       :  Creates object and calls other methods
                   Ans.  import java.util.*;
                       class Palword
                       { String w,rw;
                        void read() // input
                        { Scanner sc=new Scanner(System.in);
                         System.out.println("Enter sentence in upper case");
                         w=sc.next();
                         rw="";
                        }
                        String revword(String x)
                        {
                          if(x.equals("")) //base case
                           return(rw);
                          else
                          {
                           rw=x.charAt(0)+rw; // finding reverse word
                           return revword(x.substring(1)); //recursive case
                          }
                         }
                         void check()
                         { if(revword(w).equals(w)) // checking word=reverse word
                            System.out.println("Palindrome word "+w); // display
                          else
                            System.out.println("Not palindrome word "+w);
                         }
                         public static void main()
                         { Palword ob=new Palword();
                          ob.read();
                          ob.check();
                         }
                       }













                                                                                                                       425
                                                                                                           Recursion   425
   422   423   424   425   426   427   428   429   430   431   432