Java ChoiceFormat applyPattern()方法及示例

Java ChoiceFormat applyPattern()方法及示例

java.text.ChoiceFormat 类的 applyPattern() 方法用于通过覆盖当前的限制和格式来为当前的ChoiceFormat设置新的模式文本。这个新模式将是ChoiceFormat的limit和format的组合

语法:

public void applyPattern(String newPattern)

参数 :该方法接受 newPattern 作为参数,它是ChoiceFormat的新文本模式。

返回值: 该方法不返回任何东西。

异常: 如果指定的newPattern为空,该方法会抛出 NullPointerException

以下是说明 applyPattern( )方法的例子:

例1:

// Java program to demonstrate applyPattern() method
 
import java.text.*;
import java.util.*;
import java.io.*;
 
public class GFG {
    public static void main(String[] argv)
    {
        // creating and initializing limit
        double[] limit = { 1, 2, 3 };
 
        // creating and initializing format
        String[] format = { "sun", "mon", "tue" };
 
        // creating and initializing ChoiceFormat
        ChoiceFormat cf
            = new ChoiceFormat(limit, format);
 
        // display the result
        System.out.println("current pattern : "
                           + cf.toPattern());
 
        // applying the new pattern
        // using applyPattern() method
        cf.applyPattern("4#wed| 5#thu | 6#fri | 7#sat");
 
        // display the result
        System.out.println("\nnew pattern : "
                           + cf.toPattern());
    }
}

输出

current pattern : 1.0#sun|2.0#mon|3.0#tue

new pattern : 4.0#wed|5.0#thu |6.0#fri |7.0#sat

例2:

// Java program to demonstrate applyPattern() method
 
import java.text.*;
import java.util.*;
import java.io.*;
 
public class GFG {
    public static void main(String[] argv)
    {
        try {
            // creating and initializing limit
            double[] limit = { 1, 2, 3 };
 
            // creating and initializing format
            String[] format = { "sun", "mon", "tue" };
 
            // creating and initializing ChoiceFormat
            ChoiceFormat cf
                = new ChoiceFormat(limit, format);
 
            // display the result
            System.out.println("current pattern : "
                               + cf.toPattern());
 
            // applying the new pattern
            // using applyPattern() method
            cf.applyPattern(null);
 
            // display the result
            System.out.println("\nnew pattern : "
                               + cf.toPattern());
        }
        catch (NullPointerException e) {
            System.out.println("\nString is Null");
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出

current pattern : 1.0#sun|2.0#mon|3.0#tue

String is Null
Exception thrown : java.lang.NullPointerException

参考资料: https://docs.oracle.com/javase/9/docs/api/java/text/ChoiceFormat.html#applyPattern-java.lang.String-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程