在这篇文章中我想谈谈
MessageFormat
任务2412(task2412)中使用的类。 该类MessageFormat
旨在创建字符串。该 Java 类采用一组对象,对它们进行格式化,然后将格式化的字符串插入到模板中的适当位置。这是静态方法的一种替代(甚至补充)String.format
。首先,使用这个 Java 类的简单示例,无需创建对象,而是使用静态方法:
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format(
"At {0, time, medium} on {0, date}, there was {1} on planet {2, number, integer}.",
new Date(), event, planet);
System.out.println(result);
这里调用一个静态方法MessageFormat.format
,字符串模板以及实际上将插入到由括号分隔的位置的对象作为参数传递给该方法{}
。对象起始位置在括号中指定0
,以及格式类型(如果有)。输出将是这样的:
At 21:25:54 on 28 апр. 2018 г., there was a disturbance in the Force on planet 7.
下面的示例已经创建了该类的一个对象MessageFormat
:
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {fileCount, diskName};
MessageFormat form = new MessageFormat(
"The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
创建类对象时,MessageFormat
会将字符串模板传递给其构造函数。接下来,当调用对象的方法时format
,将插入字符串模板的对象数组作为参数传递到那里。输出将是这样的:
The disk "MyDisk" contains 1 273 file(s).
还可以确保根据变量的值选择所需的文本。运算符的一种实现if...else
,仅使用类ChoiceFormat
。这是代码:
MessageFormat form = new MessageFormat("Я могу {1} {0}.");
int count = 2;
String exercise = "подтянуться";
Object[] testArgs = {count, exercise};
double[] filelimits = {0,2,5};
String[] filepart = {"{0} раз","{0} раза","{0} раз"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
System.out.println(form.format(testArgs));
此代码根据变量的值count
更改该行的输出,如下所示:
-
如果
count = 1
结论是这样的Я могу подтянуться 1 раз.
-
如果
count = 2
结论是这样的Я могу подтянуться 2 раза.
-
如果
count = 7
结论是这样的Я могу подтянуться 7 раз.
double[] filelimits
,指定字符串输出将更改的值的限制。该数组String[] filepart
指示可以使用的字符串的各种变体。filepart[j]
从变量值中选择行选项的条件确定如下:如果 ,则选择该选项filelimits[j] =< count < filelimits[j+1]
。接下来,创建一个对象并将数组ChoiceFormat fileform
传递给其构造函数。通过该方法,我们告诉对象,当调用该方法时,对于行模板中的索引 0,使用对象中指定的格式。美好的。原则上,您可能已经有了永远不要使用 Java 类的想法,但要知道这并不是所有的花里胡哨。有这样的代码: double[] filelimits
String[] filepart
form.setFormatByArgumentIndex(0, fileform)
MessageFormat form
format
ChoiceFormat fileform
MessageFormat
MessageFormat pattform = new MessageFormat("There {0} on {1}.\n{2} {2}");
int count = 0;
Date date = new Date();
Object[] testArgs = {count, "ADisk", date, date};
double[] filelimits = {0,1,2};
String[] filepart = {"are no files","is one file","are {0} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
Format[] testFormats
= {fileform, null, DateFormat.getDateInstance(DateFormat.SHORT), DateFormat.getTimeInstance(DateFormat.SHORT)};
pattform.setFormats(testFormats);
System.out.println(pattform.format(testArgs));
这是数组的主要特征Format[] testFormats
。Format
在此数组中,我们添加负责格式化数组中定义的对象的对象(实现抽象类) Object[] testArgs
。Format[] testFormats
如果对象不需要格式化,则null
. pattform.setFormats(testFormats)
接下来,我们使用该方法告诉对象MessageFormat pattform
行模板中的所有索引都应使用数组中定义的格式Format[] testFormats
。对于此示例,输出将是:
There are no files on ADisk.
28.04.18 22:10
就是这样,希望你在解决2412题时不会遇到任何困难。
GO TO FULL VERSION