Saturday, 20 August 2016

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

6.37 (Format an integer) Write a method with the following header to format the integer with the specified width. public static String format(int number, int width) The method returns a string for the number with one or more prefix 0s. The size of the string is the width. For example, format(34, 4) returns 0034 and format( 34, 5) returns 00034. If the number is longer than the width, the method returns the string representation for the number. For example, format(34, 1) returns 34. Write a test program that prompts the user to enter a number and its width and displays a string returned by invoking format(number, width).



import java.util.Scanner;
 
public class ProgrammingExercise6_37 {
 
 public static void main(String[] args) {
  System.out.print("Enter an interger:");
  Scanner input = new Scanner(System.in);
  int number = input.nextInt();
  System.out.print("Enter the width:");
  int width = input.nextInt();
  System.out.println(format(number, width));
 
 }
 
 public static String format(int number, int width) {
  int numberOfDigit = getSize(number);
  String format = String.valueOf(number);
 
  for (int i = 0; i < width - numberOfDigit; i++) {
   format = "0" + format;
  }
 
  return format;
 }
 
 /** Return the number of digits in d */
 public static int getSize(long d) {
 
  int numberOfDigit = 1;
  while ((d = d / 10) != 0) {
   numberOfDigit++;
  }
  return numberOfDigit;
 
 }
 
}

No comments :

Post a Comment