user170008
user170008

Reputation: 1066

String.format() throws FormatFlagsConversionMismatchException

This code works fine in Java 1.6:

 public static String padLeft(String s, int n)
 {
     if (n <= 0)
         return s;
     int noOfSpaces = n * 2;
     String output;
     noOfSpaces = s.length() + noOfSpaces;
     output = String.format("%1$#" + noOfSpaces + "s", s);
     return output;
 }

But newer versions (and some other VM implementations) throw this Exception:

java.util.FormatFlagsConversionMismatchException: Mismatched Convertor =s, Flags= #
        at java.util.Formatter$Transformer.transformFromString(Formatter.java:1020)
        at java.util.Formatter$Transformer.transform(Formatter.java:861)
        at java.util.Formatter.format(Formatter.java:565)
        at java.util.Formatter.format(Formatter.java:509)
        at java.lang.String.format(String.java:1961)

Any workarounds?

Upvotes: 6

Views: 10841

Answers (2)

Jere K&#228;pyaho
Jere K&#228;pyaho

Reputation: 1315

You asked for a workaround; just use StringBuilder:

public static String padLeft(String s, int n) {
    if (n <= 0)
        return s;
    int noOfSpaces = n * 2;
    StringBuilder output = new StringBuilder(s.length() + noOfSpaces);
    while (noOfSpaces > 0) {
        output.append(" ");
        noOfSpaces--;
    }
    output.append(s);
    return output.toString();
}

Upvotes: 1

barti_ddu
barti_ddu

Reputation: 10299

Since you are using # flag in format string, you should pass Formattable as an argument (doc).

Any work arounds?

Don't use # in format string?

Upvotes: 0

Related Questions