Recipe 5.12 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 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 longer, in fact, so the ternary conditional operator is worth learning.

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 String[] formats = { "items", "item", "items"};         static ChoiceFormat myFormat = new ChoiceFormat(limits, formats);          /** report -- using conditional operator */         public static void report(int n) {                 System.out.println("We used " + n + " " + myFormat.format(n));         }         public static void main(String[] argv) {                 report(0);                  report(1);                 report(2);         } }

This generates the same output as the basic version. It is slightly longer, but more general, and lends itself better to internationalization.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net