Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata