简体   繁体   中英

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 ?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM