V4k4
V4k4

Reputation: 33

Trying to make timer read as 00:00:00

So I am trying to create a toString method that reads numbers as two digits. For example, the output of the timer is usually: 0:0:0. I would like for it to read as 00:00:00. Here is the code:

public String toString() 
{
String numberAsString = String.format ("%02d", hours + ":" + minutes + ":" + seconds);

     return numberAsString;
}

When running I get the error:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at TimeA.toString(TimeA.java:57)
at Relay.main(Relay.java:22)

Any help will be greatly appreciated!

Upvotes: 1

Views: 518

Answers (3)

rollstuhlfahrer
rollstuhlfahrer

Reputation: 4078

It has to be:

String.format ("%02d:%02d:%02d", hours, minutes, seconds);

In your code, you are first concatenating hours, minutes and seconds (yielding said 0:0:0). You need to either add the leading zero first, before concatenating. Or you can use the Format function.

The error message d != java.lang.String is, because hours + ":" + minutes + ":" + seconds returns a string. And a string cannot be formatted with the number formatter.

Upvotes: 0

jontro
jontro

Reputation: 10626

You're trying to format a string as a number (%02d). Use something like this instead

String numberAsString = String.format ("%02d:%02d:%02d", hours, minutes, seconds);

Upvotes: 0

Dave Ranjan
Dave Ranjan

Reputation: 2984

Your String.format syntax is incorrect, we cannot add in between the format, instead we leave the placeholders and provide values seperated by comma (,) that's not how it works.

String.format("%02d:%02d:%02d", hours,minutes,seconds)

say if you have hours =0, min = 0 and seconds = 0

String.format("%02d:%02d:%02d", 0L,0L,0L)

this will give output 00:00:00

Upvotes: 1

Related Questions