The i18n Cookbook - recipies for a global society

  • java cookbook
  • about the author
Home › Java Internationalization Cookbook › Resource Bundles

Java Cookbook

  • Java Internationalization Cookbook
    • Locales
    • Dates and Times
    • Numerical Systems
    • Misc
    • Resource Bundles
      • Handle plural text in a localizable manner.
      • How to combine dynamic and static data
      • Load properties from outside the classpath
      • Spell out the numeric value in a concatenated string
    • Unicode, Transliteration, and Charactersets

Handle plural text in a localizable manner.

Problem:

You want to use the correct forms for plurals in a sentence including dynamic values.

Solution:

Plurals can be very difficult to deal with.  It is not always as easy as adding an s to the end of a word.  Consider the sentence, "Enter your child(rens)'s names(s)."  That looks pretty ugly, and not human at all.

ChoiceFormat allows us to spcify blocks of text that appear depending upon a numeric value passed in.  For example:

//Create a collection of options separated by pipes, and preceded by numeric markers.
String msg = "0#no dogs| 1#a dog| 2#a couple dogs| 3#several dogs| 3<many dogs";
ChoiceFormat fmt = new ChoiceFormat(msg);
//Pass a choice into the format and that option will be selected.
System.out.println("I have " + fmt.format(2) + ".");

Now obviously our hard coded sentence in the previous example is not a good thing for localization.  We can combine a MessageFormat and ChoiceFormat to solve that issue and give us an easily localizable solution.

//Create an array of arguments.  In this case a ChoiceFormat array
Format[] choices = {new ChoiceFormat("0#no dogs| 1#a dog| 2#a couple dogs| 3#several dogs| 3<many dogs")};
//Create a message format with the type of choice
String msg = "I have {0,choice}.";
MessageFormat mft = new MessageFormat(msg);
//call the setFormats method on the MessageFormat and pass the ChoiceFormat array in
mft.setFormats(choices);
for(int x =0; x < 5; x++){
       Object[] args = {x};
        System.out.println(mft.format(args));
}

‹ Resource Bundles up How to combine dynamic and static data ›
  • resourcebundle
  • Printer-friendly version
  • Add new comment

If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.

This site is ad supported.  I hope you find something among our sponsors worth clicking. ;)

i18n search

Google
Custom Search

Search

Tags in Tags

calendar date icu4j Java Locale number format numberformat parse spellout timezone transliteration transliterator
more tags

User login

  • Create new account
  • Request new password
  • java cookbook
  • about the author