camismacho
camismacho

Reputation: 43

How Can I Correctly Format a String In Java?

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?

Upvotes: 4

Views: 8878

Answers (4)

user6232354
user6232354

Reputation:

From javadocs:

public static String format(String format, Object... args)

Returns a formatted string using the specified format string and arguments.

String.format(String format, Object... args) 

internally calls Formatter#format(Locale l, String format, Object ... args) where Locale if not specified is used which is returned by Local.getDefault()

Formatter#format(Locale l, String format, Object ... args) has this code block that is generating exception in your case.

                case 0:  // ordinary index
                    lasto++;
                    last = lasto;
                    if (args != null && lasto > args.length - 1)
                        throw new MissingFormatArgumentException(fs.toString());
                    fs.print((args == null ? null : args[lasto]), l);
                    break;

Since, args in your case is null so you are getting MissingFormatArgumentException on %02d.

Remember, this is how your format is extracted in FormatString[]

[0] -> %02d

[1] -> :

[2] -> %02d

[3] -> :

[4] -> %02d

So, at index 0, it fails and throws the exception, you see. In order to fix the exception, you need to specify arguments to String#format(String, Object ...) which in your case are specified outside either because you forgot to pass them in format. I would likely call it as a bad design as well, since null arguments should not be allowed and the function should have thrown NullPointerException with the message Atleast one argument needs to be specified to format but this is what it is. Hope, I have given a lot of details as my first answer to this community.

Upvotes: 1

You need to move the hour, minute and second variables INSIDE the parameters of the String.format

like:

@Override
public String toString() {
           String result = String.format("%02d:%02d:%02d", hour, minute, second);
           return result;
        //End toString
}

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140544

@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);

Upvotes: 1

shmosel
shmosel

Reputation: 50776

You need to pass the values as arguments to String.format():

String.format("%02d:%02d:%02d", hour, minute, second)

Upvotes: 7

Related Questions