ChoiceFormat Plural Form Selection
Pick one of several message forms by numeric range with ChoiceFormat, so 1 file, 2 files, and 0 files render grammatically correct text.
Code
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));
}
}How the snippet works
The working surface is the class FileCounts and the function main — everything else is wiring.
Repetition is confined to for (int n : new int[] {0, 1, 5}) — the rest of the file is straight-line.
Statements that matter
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);
Interactive Tools for This Topic
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.
FAQ
- How do you run ChoiceFormat Plural Form Selection?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.