Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 272
Makky Avatar asked Nov 27 '17 09:11

Makky


3 Answers

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

like image 193
YCF_L Avatar answered Nov 04 '22 23:11

YCF_L


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.

like image 34
Eugene Avatar answered Nov 04 '22 21:11

Eugene


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

like image 3
Shubhendu Pramanik Avatar answered Nov 04 '22 21:11

Shubhendu Pramanik