Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Correctly Format a String In Java?

Tags:

java

string

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?

like image 647
camismacho Avatar asked Jan 06 '23 05:01

camismacho


2 Answers

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

String.format("%02d:%02d:%02d", hour, minute, second)
like image 166
shmosel Avatar answered Jan 15 '23 23:01

shmosel


@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);
like image 36
Andy Turner Avatar answered Jan 15 '23 23:01

Andy Turner