當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java MessageFormat applyPattern()用法及代碼示例


java.text.MessageFormat類的applyPattern()方法用於通過覆蓋當前的FormatElement,FormatType和FormatStyle為當前MessageFormat設置新的模式文本。

用法:

public void applyPattern(String newPattern)

參數:此方法將字符串newPattern作為參數,這是此MessageFormat對象的新文本模式。


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

異常:如果指定的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  MessageFormat 
        MessageFormat mf 
            = new MessageFormat("{0, number, #}, {0, number, #.##}, {0, number}"); 
  
        // display the result 
        System.out.println("old pattern:"
                           + mf.toPattern()); 
  
        // applying new string pattern 
        // to this MessageFormat Object 
        // using applyPattern() method 
        mf.applyPattern("{0, time, #}"); 
  
        // display the result 
        System.out.println("\nnew pattern:"
                           + mf.toPattern()); 
    } 
}
輸出:
old pattern:{0, number, #}, {0, number, #0.##}, {0, number}

new pattern:{0, date, #}

範例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 MessageFormat 
            MessageFormat mf 
                = new MessageFormat("{0, date, #}, {1, time, #}, {0, number}"); 
  
            // display the result 
            System.out.println("old pattern:"
                               + mf.toPattern()); 
  
            // applying new string pattern 
            // to this MessageFormat Object 
            // using applyPattern() method 
            mf.applyPattern(null); 
  
            // display the result 
            System.out.println("\nnew pattern:"
                               + mf.toPattern()); 
        } 
        catch (NullPointerException e) { 
            System.out.println("\nString is Null"); 
            System.out.println("Exception thrown:" + e); 
        } 
    } 
}
輸出:
old pattern:{0, date, #}, {1, date, #}, {0, number}

String is Null
Exception thrown:java.lang.NullPointerException

參考: https://docs.oracle.com/javase/9/docs/api/java/text/MessageFormat.html#applyPattern-java.lang.String-



相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 MessageFormat applyPattern() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。