【发布时间】:2015-10-21 05:32:02
【问题描述】:
我正在尝试使用printf() 函数将零添加到用户输入的数字中。但是,我不确定语法用法。这是我到目前为止所拥有的:
public class Solution {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
final int requiredNumLength = 3;
// readign untill EOF
while (reader.hasNext()){
// getting the word form the input as a string
String word = reader.next();
// getting the number from the input as an integer
int num = reader.nextInt();
int length = String.valueOf(num).length();
if (length < requiredNumLength){
int zerosRequired = requiredNumLength - length;
//System.out.println("required zeros: " + zerosRequired);
}
// print out the columns using the word and num variables
System.out.printf("%-10s %-10s%n" , word, num);
}
}
}
这是一个使用它的例子:
input : java 023
output: java 023
(效果很好)
现在我的问题是,在一个数字小于 3 个字符的情况下,我希望能够在前面附加零以使其长度为 3。此外,这就是我想要做的if 查找一个数字需要多少个零的语句。我正在考虑对printf() 函数使用类似的东西:("%0zerosRequiredd", num); 但是,我不知道如何将它与我已经拥有的东西一起使用:System.out.printf("%-10s %-10s%n" , word, num)。有什么建议吗?
【问题讨论】:
-
对于数字说
12345,您希望它如何显示?对于号码5,您希望它如何显示? -
@TimBiegeleisen 对不起,我想我忘了提到用户只输入