Search code examples
javastring-formattingjava-6

System.out.printf method throws a flags exception


I'm reading a documentation for the Formatter.format and System.out.printf methods (Java 6) and I'm trying to practice what I learned. I'm facing to an exception that seems to me unjustified, or there is a problem of understanding the topic.

The code I wrote is simple:

final int i = -15;
System.out.printf("%1$-+06d", i);

What I expect is having an int printed with the following format

    1) pad to left ; -
    2) view the sign (négatif or positif); +
    3) complete with left zeros; 0 
    4) print on 6 columns (characters); 6

Instead, an exception is thrown and I don't know why:

Exception in thread "main" java.util.IllegalFormatFlagsException: Flags = '-+0'
at java.util.Formatter$FormatSpecifier.checkNumeric(Formatter.java:2935)
at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2890)
at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2643)
at java.util.Formatter.parse(Formatter.java:2480)
at java.util.Formatter.format(Formatter.java:2414)
at java.io.PrintStream.format(PrintStream.java:920)
at java.io.PrintStream.printf(PrintStream.java:821)
at cert.simo.formats.Test.main(Test.java:18)

Any Explainations? Thank you.


Solution

  • "-" and "0" are incompatible options. You either pad with zeros or align to the left. Down below is part of java 6 source code (v6-b14) causing this exception.

                if ((f.contains(Flags.PLUS) && f.contains(Flags.LEADING_SPACE))
                || (f.contains(Flags.LEFT_JUSTIFY) && f.contains(Flags.ZERO_PAD)))
                throw new IllegalFormatFlagsException(f.toString());