简体   繁体   English

Java字符串格式问题

[英]Java String format issue

I have a problem using the String.format() method. 使用String.format()方法时遇到问题。

So I want to create a String with a line feed, for which I use %n . 所以我想创建一个带有换行符的String,为此我使用%n

I create the string like this: 我创建这样的字符串:

for (int i = 0; i < authorNames.size(); i++) {
  tmpReturnString += authorNames.get(i) + "%n";
}

with authorNames beeing a ArrayList. authorNames一个ArrayList。 Next I want to return the formatted String: 接下来,我要返回格式化的字符串:

returnResult.setAttributes(0, String.format(tmpReturnString.substring(0, tmpReturnString.length() - 1)))

returnResult is going to be my return. returnResult将是我的回报。

But here I get a java.util.UnknownFormatConversionException: Conversion = '%' . 但是在这里,我得到了一个java.util.UnknownFormatConversionException: Conversion = '%'

Unfortunatly I have no clue how to fix this issue. 不幸的是,我不知道如何解决此问题。 Also, non of the other questions helped me. 另外,其他问题都没有帮助我。

Thanks in advance! 提前致谢!

I guess you want to remove the last new line, but by removing only one character you end up with your string ending with % . 我猜您想删除最后一行,但是通过仅删除一个字符,您最终得到的字符串以%结尾。

Do this instead: 改为这样做:

String.format(tmpReturnString.substring(0, tmpReturnString.length() - 2))

(remove 2 characters instead of just 1) (删除2个字符,而不仅仅是1个)

Or, even better, if you use apache commons: 或者,甚至更好,如果您使用apache commons:

String.format(StringUtils.join(authorNames, "%n"));
for (int i = 0; i < authorNames.size(); i++) {
  tmpReturnString += authorNames.get(i) + "%n";
}

alway return the string with two last character is "%n". 始终返回最后两个字符为“%n”的字符串。 So when you use 所以当你使用

substring(0, tmpReturnString.length() - 1)

Now the last character is '%'. 现在,最后一个字符是“%”。 The '%' is not a valid format specifier. '%'不是有效的格式说明符。

Detail in here: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html 此处的详细信息: http : //docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM