Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnknownFormatConversionException is caused by symbol '%' in String.format()

String template = "%s and '%'"; String result = String.format(template, "my string"); System.out.println(result); 

Expected:

my string and '%' 

But result is:

java.util.UnknownFormatConversionException: Conversion = ''' 

Why? How to correctly declared the sequence '%' so that it's ignored by String.format()?

like image 947
Alex Avatar asked May 23 '13 12:05

Alex


People also ask

What is %s in string format?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.

What does %s do in a string Java?

It means when % is encountered, the next character determines how to interpret the argument and insert it into the printed result. %s means interpret as string, %d is for digit, %x is digit in hexadecimal, %f is for float, etc.... It doesn't really 'do' anything, it's just a convention used for formatting text..

What is %d and %s in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What is %s format in Java?

%s in the format string is replaced with the content of language . %s is a format specifier. Similarly, %x is replaced with the hexadecimal value of number in String. format("Number: %x", number) .


1 Answers

% is already used by format specifiers so it requires an additional % to display that character:

String template = "%s and '%%'"; 
like image 90
Reimeus Avatar answered Sep 23 '22 19:09

Reimeus