1

I have a String formatter like this:

String testLogMessage = String.format("testing %s scenario %s", "BIG");
logger.info(String.format(testLogMessage, 1));

I have several tests and want to pass a number into my testLogMessage. At runtime I get this exception:

java.util.MissingFormatArgumentException: Format specifier '%s'
    at java.util.Formatter.format(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.lang.String.format(Unknown Source)

I could use a second string formatter, but is there another way to do this?

0

1 Answer 1

3

The first call to String.format expects both placeholders to be satisfied, but you only pass one value, prompting the exception.

To have the resulting string contain a placeholder for the next call to String.format, you can escape the % sign with another % sign.

'%' percent The result is a literal '%' ('\u0025')

String testLogMessage = String.format("testing %s scenario %%s", "BIG");

This will result in the string "testing BIG scenario %s", which you can use in the second String.format call. You'll want it to be a %d so you can pass an int.

String testLogMessage = String.format("testing %s scenario %%d", "BIG");
Sign up to request clarification or add additional context in comments.

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.