java String.format() 抛出 FormatFlagsConversionMismatchException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12420537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:49:31  来源:igfitidea点击:

String.format() throws FormatFlagsConversionMismatchException

javastringstring-formattingjava-7

提问by user170008

This code works fine in Java 1.6:

这段代码在 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:

但是较新的版本(以及其他一些 VM 实现)抛出了这个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?

任何解决方法?

采纳答案by Jere K?pyaho

You asked for a workaround; just use StringBuilder:

您要求解决方法;只需使用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();
}

回答by barti_ddu

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

由于您#在格式字符串中使用标志,因此您应该将Formattable作为参数 ( doc)传递。

Any work arounds?

任何解决方法?

Don't use #in format string?

不要#在格式字符串中使用?