0

I have a problem using the String.format() method.

So I want to create a String with a line feed, for which I use %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. 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.

But here I get a 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!

2
  • Line feed char is \n, try it ;) Commented Feb 27, 2017 at 11:28
  • 2
    Your substring operation removes the n from the end. Why would you do that? Commented Feb 27, 2017 at 11:28

2 Answers 2

2

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)

Or, even better, if you use apache commons:

String.format(StringUtils.join(authorNames, "%n"));
Sign up to request clarification or add additional context in comments.

1 Comment

Oh dang.. Thank you so much! Was looking at my code for too long not to see that...
0
for (int i = 0; i < authorNames.size(); i++) {
  tmpReturnString += authorNames.get(i) + "%n";
}

alway return the string with two last character is "%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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.