• Post Reply Bookmark Topic Watch Topic
  • New Topic

Formatting a string that contains percent symbol.

 
Bing Qiao
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String.format("$1$", "%not%");

The above statement causes UnknownFormatConversionException. I've tried replacing % with '\u0025' to no avail.

Any help will be appreciated, thanks!
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The format String is the first parameter in the String.format() method, so your problem is there. When I take your format and run it I get no error, though I doubt the output is what you want:

Output:

That is because you have zero argument indexes in there, so the second parameter is ignored. Now, let's assume that you meant that the "%NOT%" string is supposed to be inserted instead of the "1". The the code would look like:

The % is the sign that there is an argument to be inserted, and formatted. So I run that code and I do get the Format exception you get, mainly because I don't define a conversion to use for the formatting. If I do define a conversion ("s" because I want the value as a String), then it works fine:

Output


Read: The Formatter API for help on the Format String conversions.
 
Bing Qiao
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much Steve. That solved the problem.



 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!