Palindrome of Number and string in same user Input.

PALINDROME  OF A NUMBER AND A STRING  IN SAME USER INPUT  :



I have gone through lots of palindrome programs but did not find any Program which give me palindrome of string and Integer in same input.
I have used   Function Overloading Concept.
Following is code snippet.


 import java.util.Scanner;  
 public class PalStringAndNumber {  
      public static void main(String args[])  
       {  
           Scanner sca =new Scanner(System.in);  
           System.out.println(" Enter Number or string to check whether it is palindrome");  
 while (sca.hasNext()){  
                String input=sca.nextLine();  
                if(!input.matches("^\\d*$")){  // check for if ( string contain numbers..?)  
                     isPalindrome(input);     // call to  isPalindrome(String str) method   
                      if(isPalindrome(input)){  
                           System.out.println("you Entered " +input + " is Palindrome ");  
                      }  
                      else{  
                           System.out.println("you Entered " +input + " is NOT Palindrome");  
                      }  
                 }  
                 if( input.matches("^\\d*$")){  
                           // System.out.println("you entered number");  
                           if(isPalindrome(input)){  
            System.out.println("you Entered " +input + " is Palindrome ");  
                           }  
                           else{  
            System.out.println("you Entered " +input + " is NOT Palindrome");  
                           }  
                          }  
                 }  
       }  
       public static boolean isPalindrome(String str) {  
            int i;  
            int n=str.length();  
            String revstr="";  
            for(i=n-1;i>=0;i--)  
            revstr=revstr+str.charAt(i);  
            if(revstr.equals(str))  
            return true;  
            else  
            return false;  
 }  
       public static boolean isPalindrome(int number) {  
            int palindrome = number; // copied number into variable  
            int reverse = 0;  
          while (palindrome != 0) {  
            int remainder = palindrome % 10;  
            reverse = reverse * 10 + remainder;  
            palindrome = palindrome / 10;  
          }  
          // if original and reverse of number is equal means  
          // number is palindrome in Java  
          if (number == reverse) {  
            return true;  
          }  
          return false;  
        }  
 } 
Output :
  Enter Number or string to check whether it is palindrome  
 adi4444ida  
 you Entered adi4444ida is Palindrome   
In code
 if( input.matches("^\\d*$")) ("^\\d*$")) is regex 
 You can read more about regex in followiong link. 

Know Regex 

 Copy this code in your IDE and play around it.
If any problem in code let me know.

Happy Coding


No comments:

Post a Comment