如何将单个数字整数分成两位数

时间:2018-03-22 23:16:58

标签: java time format printf

我正在尝试用Java编写一个与时间进行比较并按顺序显示它们的程序。一切都有效,除非事实上如果有人输入例如10小时和9分钟,它打印为" 10:9"。

我希望每个数字在打印时在它前面都有一个0。 h变量代表小时,m变量代表分钟

System.out.printf("First time: %02d" , h1 , ":%02d" , m1 , "\nSecond time: %02d" , h2 , ":%02d" , m2);

1 个答案:

答案 0 :(得分:1)

I really doubt that that code is printing "10:9". It will instead likely only print First time: 10.

Your formatting strings look good, but the way that you're calling System.out.printf isn't quite right. java.io.PrintStream.printf has the following signature:

public PrintStream printf(String format, Object... args)

It expects one formatting string and then any number of Objects as arguments to be used to transform that formatting string. args is used in-order whenever an identifier is found like %d. So instead of intermixing your formatting strings and your arguments, you would want to instead write one long formatting string, and then list your arguments in the order they appear in format.

System.out.printf("First time: %02d:%02d\nSecond time: %02d%02d", h1, m1, h2, m2);