Chapter 6 Problem 37 (Format an integer)

Chapter 6 Problem 37 (Format an integer)

  • 6.37 (Format Integer) Use the following method header to write a method to format an integer to a specified width:
    public static String format(int number, int width)
    method returns a number with one or more zeros The string as a prefix. The number of digits in the string is the width. For example, format(34,4) returns 0034, and format(34,5) returns 00034. If the number is wider than the specified width, the method returns the string representation of the number. For example, format(34,1) returns 34.
    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).
  • Reference Code:
package chapter06;

import java.util.Scanner;

public class Code_37 {
    
    
    public static void main(String[] args) {
    
    
        Scanner inputScanner = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int number = inputScanner.nextInt();
        System.out.print("Enter the width: ");
        int width = inputScanner.nextInt();
        System.out.printf("The string is %s", format(number, width));
    }
    public static String format(int number, int width) {
    
    
        String numberString = String.valueOf(number);
        int lengthOfNumber = numberString.length();
        for(int i = 1;i <= width - lengthOfNumber;i++)
            numberString = "0" + numberString;
        return numberString;
    }
}

  • The results show that:
Enter the number: 34
Enter the width: 5
The string is 00034
Process finished with exit code 0

Guess you like

Origin blog.csdn.net/jxh1025_/article/details/109230308