Read Number from Console and Check if it is a Palindrome Number - Java Data Structure

Java examples for Data Structure:Algorithm

Description

Read Number from Console and Check if it is a Palindrome Number

Demo Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

  public static void main(String[] args) {

    System.out.println("Enter the number to check..");
    int number = 0;

    try {//from  w ww.  j  a  va  2s  .c  o m
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      number = Integer.parseInt(br.readLine());
    } catch (NumberFormatException ne) {
      System.out.println("Invalid input: " + ne);
      System.exit(0);
    } catch (IOException ioe) {
      System.out.println("I/O Error: " + ioe);
      System.exit(0);
    }

    System.out.println("Number is " + number);
    int n = number;
    int reversedNumber = 0;
    int temp = 0;

    while (n > 0) {
      temp = n % 10;
      n = n / 10;
      reversedNumber = reversedNumber * 10 + temp;
    }

    if (number == reversedNumber)
      System.out.println(number + " is a palindrome number");
    else
      System.out.println(number + " is not a palindrome number");
  }
}

Result


Related Tutorials