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?