Pin It

Write a menu‐driven class to accept a number from the user and check whether it is a Palindrome number or not in Java.

Program to demonstrate a menu‐driven class to accept a number from the user and check whether it is a Palindrome number or not in Java.

Palindrome number – a number is a Palindrome which when read in reverse order is same as read
in the right order. Example: 121, 11, 15451, etc.

package com.hubberspot.java.example;

import java.util.Scanner;

public class PalindromeTest {

    public static void main(String[] args) {

        char program;
        Scanner scanner = new Scanner(System.in);
        do{ 
            
            System.out.println("Press 'P' for Palindrome Test or 'E' for Exit");

            program = scanner.nextLine().toUpperCase().charAt(0);

            if(program != 'P' && program != 'E') { 
                System.out.println();
                System.out.println("You entered : " + program);
                System.out.println("Please enter P or E to proceed ... try again");
                System.out.println();
                continue;
            } 
            else { 
                switch( program )
                {
                case 'P': 
                    System.out.print( "Enter number for Palindrome checking: " );
                    
                    int number = scanner.nextInt();
                    String line = scanner.nextLine();
            
                    if( isPalindrome( number ) )
                    {
                        System.out.println( number + " is a palindrome." );
                    }
                    else
                    {
                        System.out.println( number + " is not a palindrome." );
                    }
                    break;
                }
            }

            System.out.println();
            
            if( program == 'E') { 
                System.out.println("Exiting from the program...");
            }
        }
        while(program != 'E');

    }

    private static boolean isPalindrome(int number) {
        
        int reverse = 0;
        int original = number;
        
        while(number > 0) { 
            int digit = number % 10;
            reverse = reverse * 10 + digit;
            number = number / 10;
        }
        return (reverse == original);
    }

}



Output of the program :


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot