O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Formatting with Correct Plurals

Problem

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

Solution

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.

// FormatPlurals.java 
public static void main(String argv[]) { 
    report(0); 
    report(1); 
    report(2); 
} 
/** 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"); 
else
    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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required