此代码在 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;
}
但是较新的版本(和其他一些 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)
任何解决方法?