Formatting with Correct Plurals


You’re printing something like "We used" + n + " items", but in English, “We used 1 items” is ungrammatical. You want “We used 1 item”.


Use a ChoiceFormat or a conditional statement.

Use Java’s ternary operator (cond ? trueval : falseval) in a string concatenation. Both zero and plurals get an “s” appended to the noun in English (“no books, one book, two books”), so we only need to test for n==1.

public static void main(String argv[]) { 
/** report -- using conditional operator */
public static void report(int n) { 
    System.out.println("We used " + n + " item" + (n==1?"":"s")); 

Does it work?

$ java FormatPlurals
We used 0 items
We used 1 item
We used 2 items

The final println statement is short for:

if (n==1)
    System.out.println("We used " + n + " item"); 
    System.out.println("We used " + n + " items");

This is a lot shorter, in fact, so the ternary conditional operator is worth learning.

In JDK 1.1 or later, the ChoiceFormat is ideal for this. It is actually capable of much more, but here I’ll show only this simplest use. I specify the values 0, 1, and 2 (or more), and the string values to print corresponding to each number. The numbers are then formatted according to the range they fall into:

import java.text.*; /** * Format a plural correctly, using a ChoiceFormat. */ public class FormatPluralsChoice extends FormatPlurals { static double[] limits = { 0, 1, 2 }; static ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.