实现说明
ChoiceFormat 复数形式选择可以归结为类 FileCounts和函数 main。
这个示例中仅有的重复出现在 for (int n : new int[] {0, 1, 5}) 里。
常见问题
「ChoiceFormat 复数形式选择」这个示例怎么运行?
把它当完整程序编译/解释运行即可——不需要先安装任何东西。
核心语句
String[] forms = {"no files", "one file", "{0,number,integer} files"};
ChoiceFormat byPattern = new ChoiceFormat("0#none|1#single|2#many");
ChoiceFormat counts = new ChoiceFormat(limits, forms);
代码示例
import java.text.ChoiceFormat;
import java.text.MessageFormat;
public class FileCounts {
public static void main(String[] args) {
// 半开区间 [lower,upper):0 个、恰好 1 个、其余按 "%d 个" 处理
double[] limits = {0, 1, 2};
String[] forms = {"no files", "one file", "{0,number,integer} files"};
ChoiceFormat counts = new ChoiceFormat(limits, forms);
MessageFormat fmt = new MessageFormat("scanned: {0}");
fmt.setFormatByArgumentIndex(0, counts);
for (int n : new int[] {0, 1, 5}) {
System.out.println(fmt.format(new Object[] {n}));
}
// 直接 applyPattern 也能构造:# 表示区间,| 分隔各段
ChoiceFormat byPattern = new ChoiceFormat("0#none|1#single|2#many");
System.out.println(byPattern.format(1));
System.out.println(byPattern.format(9));
}
}