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.

JavaData Integrity

Code

snippet
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

FAQ

How do you run ChoiceFormat Plural Form Selection?
Execute it straight away — the program needs nothing beyond the runtime.