“Java的MessageFormat类”的版本间的差异
来自CloudWiki
(创建页面,内容为“*MessageFormat类提供了与语言无关方式生成连接消息的方式,从而构造向终端用户显示的消息。MessageFormat获取一组对象,格式化…”) |
(没有差异)
|
2018年2月27日 (二) 13:12的版本
- MessageFormat类提供了与语言无关方式生成连接消息的方式,从而构造向终端用户显示的消息。MessageFormat获取一组对象,格式化这些对象,然后将格式化后的字符串插入到模式中的适当位置。
- 语法形式为:
MessageFormat.format(String pattern, Object… arguments)
- pattern是格式化模式,arguments是一组需要格式化的对象。而格式化模式中格式化元素的形式可以有三种表示方式:
{ArgumentIndex} {ArgumentIndex, FormatType} {ArgumentIndex, FormatType, FormatStyle}
- 其中,ArgumentIndex表示要格式化对象的索引位置,第一个要格式化对象的索引值为0;FormtType的取值为number、date、time、choice其中之一;FormatStyle取值可以是short、medium、long、full、integer、currency、percent、SubformatPattern。
- 例如,语句块1
//pattern格式中{0}表示要格式化对象的索引位置 String pattern = "{0} is very interesting"; System.out.println(MessageFormat.format(pattern, "Java"));
- 运行结果为:
Java is very interesting
- 例如,语句块2
int planet = 7; String event = "a disturbance in the Force"; /* * {1, time}表示以time格式输出索引位置为1的格式化对象的取值; * {1, date}表示以date格式输出索引位置为1的格式化对象的取值; * {2}表示以字符串的形式输出索引位置为2的格式化对象的取值; * {0, number, integer}表示以数值格式中的整型样式输出索引位置为0的格式化对象的值; */ String pattern = "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}."; String result = MessageFormat.format(pattern, planet, new Date(), event); System.out.println(result);
- 运行结果为:
At 22:30:05 on 2018-2-17, there was a disturbance in the Force on planet 7.
返回 Java程序设计