题目描述:
使用下面的方法头编写一个方法,用于将整数格式化为指定宽度:
public static String format(int number, int width)
方法为数字 number 返回一个带有一个或多个以 0 作为前缀的字符串。字符串的位数就是宽度。比如,format(34,4)返回 0034,format(34,5)返回 00034。如果数字宽于指定宽度,方法返回该数字的字符串表示。比如,format(34,l)返回 34。编写一个测试程序,提示用户输入一个数字以及宽度,显示通过调用 format(number,width)返回的字符串。
破题:
- 将整型number转为字符串numberString;
- 采用循坏将字符“0”连接在numberString前面。
代码:
import java.util.Scanner;
public class Test13 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number and it's width(eg.(34 1)):");
int number = in.nextInt();
int width = in.nextInt();
System.out.println(format(number,width));
in.close();
}
public static String format(int number, int width)
{
String numberString = String.valueOf(number);
int length = numberString.length();
if(length >= width)
return numberString;
for(int i = 0; i < width - length; i++)
{
numberString = "0" + numberString;
}
return numberString;
}
}