Chapter Six Question 37 (Format An Integer)-Formatting Practice Answers

Posted May 26, 20202 min read

6.37(Format integer) Use the following method header to write a method for formatting an integer to a specified width:

public static String format(int number, int width)

The method returns a string prefixed with one or more zeros for the number number. 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 a 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).

Here is the reference answer code:

//https://cn.fankuiba.com
import java.util.Scanner;

public class Ans6_37_page205 {
    public static void main(String []args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number:");
        int number = input.nextInt();
        System.out.print("Enter the number width:");
        int width = input.nextInt();
        System.out.println(format(number, width));
    }
    public static String format(int number, int width) {
        String format = "";
        int numberLenth =(number + ""). length();
        if(numberLenth <width) {
            for(int i = 1; i <= width-numberLenth; i ++)
                format = format + "0";
            return format + number;
        }
        else
            return "" + number; //String strNumber = String.valueOf(number)
    }
}

Applicable to Java language programming and data structure(The Basics)(11th edition of the original book) Java language programming(The Basics)(10th/11th edition of the original book) More