Java Message Formatter无法正常工作

我有String模板

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

即使我提供的所有三个参数仍然不起作用

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

输出是:

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

看输出,它输出{2}而不是3,我找不到它为什么不起作用.这是一个错误还是我遗失了什么?

最佳答案
你的问题在于单引号’你必须使用double’而不是一个:

xxxxx''x

阅读有关单引号的文档(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 “{}”.

转载注明原文:Java Message Formatter无法正常工作 - 代码日志