📌  相关文章
📜  Java中的 ChoiceFormat setChoices() 方法及示例

📅  最后修改于: 2022-05-13 01:55:31.985000             🧑  作者: Mango

Java中的 ChoiceFormat setChoices() 方法及示例

Java.text.ChoiceFormat类的setChoices()方法用于在 Choiceformat 对象中使用定义的限制和格式设置新的 Choice 项。

句法:

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

参数:此方法采用以下参数:

  • 限制:这是包含选择项限制的双精度值数组。
  • 格式:这是字符串值的数组,将包含选择项的格式。

返回值:此方法不返回任何内容。

异常:如果限制或格式为空,此方法将抛出NullPointerException

以下是说明setChoices()方法的示例:

示例 1:

// Java program to demonstrate
// setChoices() method
  
import java.text.*;
import java.util.*;
import java.io.*;
  
public class GFG {
    public static void main(String[] argv)
    {
        try {
  
            // creating and initializing ChoiceFormat
            ChoiceFormat cf1
                = new ChoiceFormat(
                    "4#wed| 5#thu | 6#fri | 7#sat");
  
            // creating and initializing new double array
            double[] newlimit = { 1, 2, 3 };
  
            // creating and initializing new String array
            String[] newformat = { "sun", "mon", "tue" };
  
            // setting the limit and format in
            // ChoiceFormat Object
            // using setChoices() method
            cf1.setChoices(newlimit, newformat);
  
            // display the result
            System.out.print("updated Choiceformat object: "
                             + cf1.toPattern());
        }
        catch (NullPointerException e) {
            System.out.println("\nLimit or Format is null");
            System.out.println("Exception thrown: " + e);
        }
    }
}
输出:
updated Choiceformat object: 1.0#sun|2.0#mon|3.0#tue

示例 2:

// Java program to demonstrate
// setChoices() method
  
import java.text.*;
import java.util.*;
import java.io.*;
  
public class GFG {
    public static void main(String[] argv)
    {
        try {
  
            // creating and initializing ChoiceFormat
            ChoiceFormat cf1
                = new ChoiceFormat(
                    "4#wed| 5#thu | 6#fri | 7#sat");
  
            // creating and initializing new double array
            double[] newlimit = null;
  
            // creating and initializing new String array
            String[] newformat = { "sun", "mon", "tue" };
  
            // setting the limit and format in
            // ChoiceFormat Object
            // using setChoices() method
            cf1.setChoices(newlimit, newformat);
  
            // display the result
            System.out.print("updated Choiceformat object: "
                             + cf1.toPattern());
        }
        catch (NullPointerException e) {
            System.out.println("Limit or Format is null");
            System.out.println("Exception thrown: " + e);
        }
    }
}
输出:
Limit or Format is null
Exception thrown: java.lang.NullPointerException

参考: https://docs.oracle.com/javase/9/docs/api/ Java/text/ChoiceFormat.html#setChoices-double:A-java.lang.String:A-