String.format()引发FormatFlagsConversionMismatchException [英] String.format() throws FormatFlagsConversionMismatchException
本文介绍了String.format()引发FormatFlagsConversionMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码在Java 1.6中可以正常工作:
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;
}
但是较新的版本(和其他一些VM实现)抛出此Exception
:
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)
有什么解决方法吗?
推荐答案
您要求一种解决方法;只需使用 StringBuilder :
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();
}
这篇关于String.format()引发FormatFlagsConversionMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文