Java message formatter not working

I have a string pattern

xxxxxxxx xxxxx-xx: [{0}] xxxxxxx xxxxx xxxxxx xxxxxx [{1}] xxxxxx xxxx xxxxx'x xxxxx xxxxxx xxxx [{2}] 

Even if I provide all three arguments that still don't work

 public static void main(String[] args) { String s = "xxxxxxxx xxxxx-xx: [{0}] xxxxxxx xxxxx xxxxxx xxxxxx [{1}] xxxxxx xxxx xxxxx'x xxxxx xxxxxx xxxx [{2}]"; System.out.println(MessageFormat.format(s,"1","2","3")); } 

Output:

 xxxxxxxx xxxxx-xx: [1] xxxxxxx xxxxx xxxxxx xxxxxx [2] xxxxxx xxxx xxxxxx xxxxx xxxxxx xxxx [{2}] 

See the output, the output of which is {2} instead of 3 , I can not find why it does not work. Is this a mistake or am I missing something?

+5
source share
3 answers

Your problem is in the single quote ' you need to use double '' instead of one:

 xxxxx''x 

Read the single quote documentation ( MessageFormat )

Inside String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, the drawing "'{0}'" represents the string "{0}", not the FormatElement. A single quote must itself be represented by double single quotes '' throughout the String. For example, the pattern string "'{' '}'" is interpreted as the sequence "{(beginning of quote and left curly brace)" (single quote) and} '(right curly brace and end of quote), not' {'and'} '(left and right braces quoted): a representation of the string "{'}", not "{}".

+9
source

This is the apostrophe, you need to avoid it with the help of another apostrophe, for example: ''xxx . Its in doc btw:

Inside a string, '' (two single quotes) is a single quotation mark.

+3
source

This is because you have ' in your line. You need to run away from him or you are missing.

+2
source

Source: https://habr.com/ru/post/1273679/


All Articles