How to format string in Java?

I find it hard to format String in Java. What I'm trying to do now is create a toString method that will print integers in the clock format, for example: 12:09:05, where 12 is an hour, 9 minutes and 5 seconds.

This is the code in my Clock class that I am trying to execute to format a string:

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

The problem I am facing is that when I run my driver program, everything works until I try to print the clock object.

System.out.println(clock1);

I get this exception:

Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier "% 02d" in java.util.Formatter.format (Formatter.java:2519) in java.util.Formatter.format (Formatter.java:2455) in java .lang.String.format (String.java:2940) in Clock.toString (Clock.java:62) in java.lang.String.valueOf (String.java:2994) in java.io.PrintStream.println (PrintStream. java: 821) in TestClock.main (TestClock.java:69)

I read about String formatting, and I get from it that it is almost the same as printf. The code I have works fine if I use it in the printf statement. I looked at examples on the Internet, but they all display formatting using integers, not variables.

, - , ? , Formatter.format String.format. , , , String?

+4
4

String.format():

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

@shmosel , ; , , , , ( , ):

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

4 String:

  • result, String.format("%02d:%02d:%02d"); , 3 ;
  • hour, minute second, .

, -, hour, minute second, : hour, minute, second :

String result = String.format("%02d:%02d:%02d", hour, minute, second);
+1

javadocs:

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

, .

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

Formatter#format(Locale l, String format, Object ... args), Locale, , Local.getDefault()

Formatter#format(Locale l, String format, Object ... args) , .

                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;

, MissingFormatArgumentException %02d.

, FormatString[]

[0] β†’ % 02d

[1] β†’ :

[2] β†’ % 02d

[3] β†’ :

[4] β†’ % 02d

, 0 . , String#format(String, Object ...), , format. , null , NullPointerException Atleast one argument needs to be specified to format, , . , .

+1

, INSIDE String.format

:

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

All Articles