Friday, 19 August 2016

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

*6.4 (Display an integer reversed) Write a method with the following header to display an integer in reverse order: public static void reverse(int number) For example, reverse(3456) displays 6543. Write a test program that prompts the user to enter an integer and displays its reversal.

import java.util.Scanner;
 
public class ProgrammingExercise6_4 {
 public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter an integer:");
  int number = input.nextInt();
 
  System.out.print("The reversal is " + reverse(number));
 
 }
 
 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;
 }
}

No comments :

Post a Comment