I'm having difficulty formatting a String in Java. What I'm currently trying to do is create a toString method that will print out integers in a clock format, like so: 12:09:05, where 12 is the hour, 9 the minute, and 5 the second.
This is the code in my Clock class I have been trying to get to work to format the String:
//toString Method
public String toString(){
String result = String.format("%02d:%02d:%02d"), hour, minute, second;
return result;
}//End toString
The problem I'm having is that when I run my driver program, everything works until I try to print out the clock object.
System.out.println(clock1);
I get this exception:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%02d' at java.util.Formatter.format(Formatter.java:2519) at java.util.Formatter.format(Formatter.java:2455) at java.lang.String.format(String.java:2940) at Clock.toString(Clock.java:62) at java.lang.String.valueOf(String.java:2994) at java.io.PrintStream.println(PrintStream.java:821) at TestClock.main(TestClock.java:69)
I've read up on String formatting, and what I get from it is that it's pretty much the same as printf. The code I have works fine if I use it in a printf statement. I've looked at examples on the internet, but they all show formatting using integers and not variables.
I'm hoping someone could enlighten me on the proper way to perform String formatting? I've seen people use Formatter.format instead of String.format. I'm also wondering if maybe I need to call in my accessors instead of trying to directly use the variables in the String?
You need to pass the values as arguments to String.format()
:
String.format("%02d:%02d:%02d", hour, minute, second)
@shmosel's answer tells you what to do; I thought it would be useful to explain what you had written compiled but failed at runtime (not least because it took me a few reads to grok it):
String result = String.format("%02d:%02d:%02d"), hour, minute, second;
You are actually declaring 4 String
variables here:
result
, which is assigned the value of String.format("%02d:%02d:%02d")
; this method call fails because 3 integer parameters need to be passed in addition;hour
, minute
and second
, which are uninitialized and unused.Assuming you have three integer member variables called hour
, minute
and second
, you have misplaced the bracket: hour, minute, second
need to go inside the parentheses:
String result = String.format("%02d:%02d:%02d", hour, minute, second);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With