Friday, 19 August 2016

Chapter 6 Exercise 3, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**6.3 (Palindrome integer) Write the methods with the following headers // Return the reversal of an integer, i.e., reverse(456) returns 654 public static int reverse(int number) // Return true if number is a palindrome public static boolean isPalindrome(int number) Use the reverse method to implement isPalindrome. A number is a palin- drome if its reversal is the same as itself. Write a test program that prompts the user to enter an integer and reports whether the integer is a palindrome.

public class ProgrammingExercise6_3 {
 public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter an integer:");
  int number = input.nextInt();
 
  if (isPalindrome(number)) {
   System.out.print(number + " is a palindrome");
  } else {
   System.out.print(number + " is not a palindrome");
  }
 
 }
 
 public static int reverse(int number) {
  int reverse = 0;
  int digit;
 
  do {
   digit = number % 10;
   reverse = reverse * 10 + digit;
   number /= 10;
  } while (number != 0);
 
  return reverse;
 }
 
 public static boolean isPalindrome(int number) {
 
  return (number == reverse(number));
 
 }
 
}

2 comments :

  1. Hi why is number put in bracket in the line :

    if (isPalindrome(number))

    ReplyDelete
  2. @Karen William
    we need check if user input is a palindrome or not. The user input is integer type and is stored in number.
    "int number = input.nextInt();"
    that is what we are checking is Palindrome or not. If is Palindrome true will be returned else false will be returned.

    ReplyDelete