Writing plural and singular words using ChoiceFormat in MessageFormat

Posted on October 25, 2007 by prashant
Filed Under Programming.

In Dekoh Photos application I wanted to internationalize String that represents the number of comments made on a Photo.

So when there are no comments made i wanted to display “No Comments”, when there is 1 comment i wanted to display “1 Comment” and if there are more than one comment i wanted to display “n Comments”.

Using the following neat trick that employs choice format all these possibilities can be addressed in one message key.

    private static final MessageFormat comments = new MessageFormat(
            "{0, choice, 0#No Comments|1#{0} comment|2#{0} comments}");

    public static void main(String[] args)
    {
        String zero = comments.format(new Object[]{0});
        System.out.println("zero= " + zero);
        String one = comments.format(new Object[]{1});
        System.out.println("one = " + one);
        String two = comments.format(new Object[]{2});
        System.out.println("two = " + two);
        String three = comments.format(new Object[]{3});
        System.out.println("three = " + three);
    }

Will print :

zero= No Comments
one = 1 comment
two = 2 comments
three = 3 comments

So the trick likes in this line

"{0, choice, 0#No Comments|1#{0} comment|2#{0} comments}");

{0} represents the number of comments, which will be supplied at runtime as a value. If this value is anything more than 1 {0} Comments will be returned.

Cool, eh ?

Share:
  • del.icio.us
  • Digg
  • blogmarks
  • DZone
  • Furl
  • Ma.gnolia
  • Netvouz
  • Reddit
  • Simpy
  • SphereIt
  • Spurl
  • StumbleUpon
  • Technorati

Comments

Leave a Comment