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


Java ChoiceFormat format()用法及代碼示例


java.text.ChoiceFormat類的format()方法用於獲取附加限製字符串格式的字符串生成器,該格式值的特定限製值作為參數傳遞,該文本作為參數傳遞給該方法。

用法:

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

參數:此方法采用以下參數,如下所示


  • number:這是選擇格式對象的特定限製,必須為其找到格式並附加格式
  • toAppendTo:這是要附加格式的新文本
  • status:確定是否沒有特殊狀態要返回

返回值:此方法以StringBuffer對象的形式返回文本和格式的附加值。

異常:如果toAppendto值為null,則此方法引發NullPointerException。

下麵是說明format()方法的示例:

示例1:

// Java program to demonstrate 
// format() 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 StringBuffer 
            StringBuffer str = new StringBuffer("Sun"); 
  
            // getting the required format with appended text 
            // ChoiceFormat Object 
            // using format() method 
            StringBuffer vlaue = cf1.format(6, str, null); 
  
            // display the result 
            System.out.print("Formated text with appended value: "
                             + vlaue.toString()); 
        } 
        catch (NullPointerException e) { 
            System.out.println("str is null"); 
            System.out.println("Exception thrown: " + e); 
        } 
    } 
}
輸出:
Formated text with appended value: Sunfri 

示例2:

// Java program to demonstrate 
// format() 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 StringBuffer 
            StringBuffer str = null; 
  
            // getting the required format with appended text 
            // ChoiceFormat Object 
            // using format() method 
            StringBuffer vlaue = cf1.format(6, str, null); 
  
            // display the result 
            System.out.print("Formated text with appended value: "
                             + vlaue.toString()); 
        } 
        catch (NullPointerException e) { 
            System.out.println("str is null"); 
            System.out.println("Exception thrown: " + e); 
        } 
    } 
}
輸出:
str is null
Exception thrown: java.lang.NullPointerException

參考: https://docs.oracle.com/javase/9/docs/api/java/text/ChoiceFormat.html#format-double-java.lang.StringBuffer-java.text.FieldPosition-



相關用法


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