The Java Program: Choice.java

  1 import java.text.Format;
  2 import java.text.MessageFormat;
  3 import java.text.NumberFormat;
  4 import java.text.ChoiceFormat;
  5 
  6 public class Choice {
  7 
  8    public static void main (String[] args) {
  9 
 10       final MessageFormat mf = new MessageFormat ("{0} has {1}.");
 11       
 12       final double[] limits = {0,1,2};
 13       final String [] m = {"no new e-mail messages",
 14                            "one new e-mail message",
 15                            "{2} new e-mail messages"};
 16 
 17       final ChoiceFormat cf = new ChoiceFormat (limits, m);
 18       final Format [] formats = {null, cf, NumberFormat.getInstance()};
 19       mf.setFormats (formats);
 20 
 21       // Print the pattern
 22       System.out.println (mf.toPattern());
 23       System.out.println ();
 24 
 25       for (int i=-1; i<4; i++) {
 26       
 27          final Integer count = new Integer (i);
 28 
 29          // Assign the first 4 objects from the bundle to an array.
 30          final Object[] arguments = {"Ryan", count, count};
 31 
 32          // Format the objects in the arguments array to a string.
 33          final String result = mf.format (arguments);
 34 
 35          // Print the formatted string.
 36          System.out.println (result);
 37       }
 38    }
 39 }