9

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 ?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Makky
  • 17,117
  • 17
  • 63
  • 86

3 Answers3

16

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 "{}".

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
4

It's the apostrophe indeed, you need to escape it with another apostrophe, like : ''xxx. Its in the doc btw:

Within a String, '' (two single quotes ) represents a single quote.

Eugene
  • 117,005
  • 15
  • 201
  • 306
3

It's because you have ' in your String. You need to escape it or you are missing one.

Shubhendu Pramanik
  • 2,711
  • 2
  • 13
  • 23