6.37(格式化整數)使用下面的方法頭編寫一個方法,用於將整數格式化爲指定寬度:java
public static String format(int number, int width)數據結構
方法爲數字number返回一個帶有一個或多個以0做爲前綴的字符串。字符串的位數就是寬度。好比,format(34,4)返回0034,format(34,5)返回00034。若是數字寬於指定寬度,方法返回該數字的字符串表示。好比,format(34,1)返回34。ui
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)code
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).orm
下面是參考答案代碼:ci
// 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) } }
適用Java語言程序設計與數據結構(基礎篇)(原書第11版)Java語言程序設計(基礎篇)(原書第10/11版)更多字符串