Class ChoiceFormat in Java With Example

This post will cover ChoiceFormat in java, ChoiceFormat java in detail, ChoiceFormat java example, ChoiceFormat java APIs, ChoiceFormat java class structure.

Class ChoiceFormat in java

ChoiceFormat is a subclass of Format. It converts a number to the string in the same way on how java switch case works. Every ChoiceFormat has an array of doubles. They present their limits and an array of Strings. They represent format. When format() method acts to format a number y, the representation will be

Ads code goes here
limits[j]<=y<limits[j+1]

if y is less than the first element of the given array, then the first element is used. In case y is greater than the last element is taken and used. once j value can be determined, the indexed String is returned from format() method.[j is used as the index of the array of String].

Another example:

 X matches j if and only if limit[j] ≤ X < limit[j+1]

A ChoiceFormat object can be created by taking care of “limit” and “format” into a single string. This single string is known as a pattern.

A ChoiceFormat enables us to attach a format to a range of numbers. It is generally used in a MessageFormat for handling plurals(many cases). The choice is specified with an ascending list of doubles, where each item specifies a half-open interval up to the next item.

Example of pattern

ChoiceFormat myChoiceFormat=new ChoiceFormat("0#cases|1#case|2#cases");

A choice object is created from cases. When it formats the number 0 or any number greater than or equal to 2, it returns “case” when it formats the number 1.

In this scenario, the # symbol is used to separate the limit number from String and | symbol is used to separate the different cases.

For a better idea of formatting please check SimpleDateFormat and MessageFormat.

The ChoiceFormat class is a concrete subclass of NumberFormat that maps numerical ranges to strings or formats.ChoiceFormat objects are used most often by MessageFormat objects to handle plurals, verb agreement, and other such issues.

The ranges in a ChoiceFormat are specified as an ascending array of double values, where each number is the bottom end of a range. A value is mapped to a format when it falls within the range for that format. If the value does not fall in any of the ranges, it is mapped to the first or the last format, depending on whether the value is too low or too high. For example, consider the following code:

double[] limits = {1, 10, 100};
String[] labels = {"simple", "medium", "complex"}
ChoiceFormat cf = new ChoiceFormat(limits, labels);

Any number greater than or equal to one and less than 10 is mapped to the format “simple”. Any number greater than or
equal to 10 and less than 100 is mapped to “medium”. Numbers greater than or equal to 100 are mapped to “complex”.
Furthermore, numbers less than one are also mapped to “simple”.

READ  Class Observable in Java

The nextDouble() and previousDouble() methods can generate double values that are higher or lower than other double values. These methods provide another way to specify the limits used by a ChoiceFormat object.

As shown above, we can create a ChoiceFormat object by specifying the limits and formats in two separate arrays.
We can also create a ChoiceFormat object using a pattern string that specifies the limits and formats. The string is of the form:
[limit1]#[format1]|[limit2]#[format2]|…

A < character can be used in place of the # to indicate that the next higher number, as determined by nextDouble(),
should be used as the limit. The toPattern() method can be used to generate the pattern string for an existing
ChoiceFormat object.

Note that we create ChoiceFormat objects directly, rather than through factory methods. This is because ChoiceFormat does not implement any locale-specific behavior. To produce properly internationalized output, the formats for a ChoiceFormat should come from a ResourceBundle instead of being embedded in the code.

ChoiceFormat java class structure

public class java.text.ChoiceFormat extends java.text.NumberFormat {
// Public Constructors
public ChoiceFormat(String newPattern);
public ChoiceFormat(double[] limits, String[] formats);
// Class Methods
public static final double nextDouble(double d);
public static double nextDouble(double d, boolean positive);
public static final double previousDouble(double d);
// Public Instance Methods
public void applyPattern(String newPattern);
public Object clone(); // Overrides NumberFormat
public boolean equals(Object obj); // Overrides NumberFormat
public StringBuffer format(long number, StringBuffer toAppendTo,FieldPosition status);
// Defines NumberFormat
public StringBuffer format(double number, StringBuffer toAppendTo,FieldPosition status);
// Defines NumberFormat
public Object[] getFormats();
public double[] getLimits();
public int hashCode(); // Overrides NumberFormat
public Number parse(String text, ParsePosition status);
// Defines NumberFormat
public void setChoices(double[] limits, String[] formats);
public String toPattern();
}

The details of the class structure are given as follows:

public ChoiceFormat(String newPattern);

public ChoiceFormat(String newPattern) constructor creates a ChoiceFormat that uses the limits and formats represented by the given pattern string.

Parameter
newPattern – The pattern string.

public ChoiceFormat(double[] limits, String[] formats);

public ChoiceFormat(double[] limits, String[] formats) constructor creates a ChoiceFormat that uses the given limits and format strings.

Parameter
limits – An array of limits. Each element is the lower end of a range that runs up through, but not including, the next element.
formats – An array of format strings that correspond to the limit ranges.

public static final double nextDouble(double d);

public static final double nextDouble(double d) method returns the least double greater than d. Calling this method is equivalent to nextDouble(d,true).

This method returns the least double that is greater than d.

Parameter
d – A double value.

public static double nextDouble(double d, boolean positive);

public static double nextDouble(double d, boolean positive) method finds the next higher or next lower double value from d, depending on the value of positive. If positive is true, the method returns the least double greater than d. Otherwise, the method returns the greatest double less than d.

This method returns If positive is true, the least double that is greater than d. If positive is false, the greatest double that is less than d.

READ  Abstract Interface Member in Java

Parameter
d – A double value.
positive – A boolean value that specifies whether to return the next higher or next lower value.

public static final double previousDouble(double d);

public static final double previousDouble(double d) method returns the greatest double less than d. Calling this method is equivalent to nextDouble(d,false).

This method returns the greatest double that is less than d.

Parameter
d – A double value.

public void applyPattern(String newPattern);

public void applyPattern(String newPattern) method tells this ChoiceFormat to use the limits and formats represented by the given formatting pattern string. Pattern strings for ChoiceFormat objects are described above in the class description.

Parameter
newPattern – The pattern string.

public Object clone();

public Object clone() method creates a copy of this ChoiceFormat and returns it.

This method returns a copy of this ChoiceFormat.

public boolean equals(Object obj);

public boolean equals(Object obj) method returns true if obj is an instance of ChoiceFormat and is equivalent to this ChoiceFormat.

This method returns true if the objects are equal; false if they are not.

Parameter
obj – The object to be compared with this object.

public StringBuffer format(double number,StringBuffer toAppendTo, FieldPosition status);

public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition status) method formats the given number and appends the result to the given StringBuffer.

This method returns the given StringBuffer with the String corresponding to the given number appended to it.

Parameter
number – The double value to be formatted.
toAppendTo – A StringBuffer on which to append the formatted information.
status – Ignored.

public StringBuffer format(long number,StringBuffer toAppendTo, FieldPosition status);

public StringBuffer format(long number,StringBuffer toAppendTo, FieldPosition status) method formats the given number and appends the result to the given StringBuffer.

This method returns the given StringBuffer with the String corresponding to the given number appended to it.

Parameter
number – The long value to be formatted.
toAppendTo – A StringBuffer on which to append the formatted information.
status – Ignored.

public Object[] getFormats();

public Object[] getFormats() method returns an array containing the current set of format strings.

This method returns an array that contains the format strings.

public double[] getLimits();

public double[] getLimits() method returns an array that contains the current set of limits.

This method returns an array that contains the limit values.

public int hashCode();

public int hashCode() method returns a hashcode for this ChoiceFormat.

This method returns a hashcode for this object.

public Number parse(String text, ParsePosition status);

public Number parse(String text, ParsePosition status) method parses a number from the given string, starting from the given position. The method returns a Number object that encapsulates the value that corresponds to the longest format string that matches the text starting at the given position. If there is no matching format string, the method returns the value Double.NaN.

If there is a matching format string, the index value of the given ParsePosition object is incremented by the
length of that format string.

READ  IllegalAccessError in Java

This method returns a Number object that encapsulates the value that corresponds to the longest format string that matches the text that starts at the given position. If there is no matching format string, the value Double.NaN is returned.

Parameter
text – The string to be parsed.
status – A ParsePosition object that can specify a position in the string.

public void setChoices(double[] limits, String[] formats);

public void setChoices(double[] limits, String[] formats) method sets the limits and format strings that this ChoiceFormat uses.

Parameter
limits – An array of limits. Each element is the lower end of a range that runs up through, but not including, the next element.
formats – An array of format strings that correspond to the limit ranges.

public String toPattern();

public String toPattern() method returns a string that represents the limits and format strings of this ChoiceFormat. Pattern strings for ChoiceFormat objects are described above in the class description.

This method returns the pattern string of this ChoiceFormat.

Apart from these methods, the ChoiceFormat class also has inherited methods from class- Object. They are as follows:

  • finalize()
  • notifyAll()
  • wait()
  • wait(long, int)
  • getClass()
  • notify()
  • toString()
  • wait(long)

The ChoiceFormat class also has inherited methods from NumberFormat. They are as follows:

  • format(long number)
  • getMaximumIntegerDigits()
  • getMinimumIntegerDigits()
  • isParseIntegerOnly()
  • setGroupingUsed(boolean)
  • setMaximumIntegerDigits(int)
  • format(double)
  • format(Object, StringBuffer,FieldPosition)
  • getMaximumFractionDigits()
  • getMinimumFractionDigits()
  • isGroupingUsed()
  • parse(String)
  • parseObject(String,ParsePosition)
  • setMaximumFractionDigits(int)
  • setMinimumFractionDigits(int)
  • setMinimumIntegerDigits(int)
  • setParseIntegerOnly(boolean)

The ChoiceFormat class also has inherited one methods from Format. That is as follows:

  • parseObject(String)

ChoiceFormat java in details

If there is no match found, then either the first or last index is used, depending on whether the number (X) is too low or too high.

If the limit array is not in ascending order, the results of the formatting will be incorrect. ChoiceFormat also accepts \u221E as equivalent to infinity(INF).

Note: ChoiceFormat differs from the other Format classes in that you create a ChoiceFormat object with a constructor (not with a getInstance style factory method).

The factory methods aren’t necessary because ChoiceFormat doesn’t require any complex setup for a given locale. In fact, ChoiceFormat doesn’t implement any locale-specific behavior

ChoiceFormat java example

 

  • limits = {1,2,3,4,5,6,7}
    formats = {“Sun”,”Mon”,”Tue”,”Wed”,”Thur”,”Fri”,”Sat”}
  • limits = {0, 1, ChoiceFormat.nextDouble(1)}
    formats = {“no files”, “one file”, “many files”}
    (nextDouble can be used to get the next higher double, to make the half-open interval.)
 double[] limits = {1,2,3,4,5,6,7};
 String[] dayOfWeekNames = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
 ChoiceFormat form = new ChoiceFormat(limits, dayOfWeekNames);
 ParsePosition status = new ParsePosition(0);
 for (double i = 0.0; i <= 8.0; ++i) {
     status.setIndex(0);
     System.out.println(i + " -> " + form.format(i) + " -> "
                              + form.parse(form.format(i),status));
 }

important ChoiceFormat java apis

public void applyPattern(String newPattern);

We can change the pattern by using the applyPattern() method if we wish to change.

public String toPattern();

We can get the pattern information by applying toPattern() method in the form of String.

Reference: Oracle ChoiceFormat

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *