javajava-8messageformat

Java Message Formatter is not working


I have String template

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

Even if I provide all the three arguments still not working

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"));
}

The output is :

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

See output, Its outputting the {2} instead of 3, I cannot find why it is not working. Is it a bug or I am missing something ?


Solution

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

    xxxxx''x
    

    Read the documentation about single quote (MessageFormat)

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