0

I am trying to write a program in Java that compares to times and displays them in order. Everything works, except for the fact that if someone entered for example a 10 for the hour, and a 9 for the minute, it prints as "10:9".

I would like for each single digit to have a 0 in front of it when it prints. The h variable stands for hour and the m variable stands for minute

System.out.printf("First time: %02d" , h1 , ":%02d" , m1 , "\nSecond time: %02d" , h2 , ":%02d" , m2);
  • If those are times of day, use the `LocalTime` class from java.time (the modern Java date and time API). Its `toString` method produces a string like `10:09` (granted that its seconds are 0, which I presume they will be in your case). If your times are amounts of time or durations, use the `Duration` class, but keep your own formatting logic. – Ole V.V. Mar 23 '18 at 08:49

1 Answers1

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);
CollinD
  • 7,304
  • 2
  • 22
  • 45