当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ChoiceFormat applyPattern()用法及代码示例


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

用法:

public void applyPattern(String newPattern)

参数:此方法将newPattern作为参数,这是ChoiceFormat的新文本模式。


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

异常:如果指定的newPattern为null,则此方法引发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-



相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 ChoiceFormat applyPattern() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。