2012-01-19 5 views
2

javaのMessageFormat.formatメソッドでFieldPosition引数をどのように使用しますか?私がオンラインで見たすべての例では、FieldPosition引数は使用されていません。この議論は何に使われていますか?私はここの仕様を見ています:http://docs.oracle.com/javase/1.5.0/docs/api/java/text/MessageFormat.html。メソッドのシグネチャは下にコピーされます。Java MessageFormat.formatメソッドでFieldPosition引数を使用するには?

public final StringBuffer format(Object[] arguments, 
           StringBuffer result, 
           FieldPosition pos) 

答えて

2

のFieldPositionは、2つのインデックスでフォーマットされた出力内のフィールドの位置を追跡:フィールドの最初の文字とフィールドの最後の文字のインデックスのインデックスを。

あなたはMessageFormat.formatで使用されるのFieldPosition引数についてはDateFormat

FieldPosition pos = new FieldPosition(DateFormat.YEAR_FIELD); 
FieldPosition pos2 = new FieldPosition(DateFormat.MONTH_FIELD); 

について

NumberFormat numForm = NumberFormat.getInstance(); 
    StringBuffer dest1 = new StringBuffer(); 
    FieldPosition pos = new FieldPosition(NumberFormat.INTEGER_FIELD); 
    BigDecimal bd1 = new BigDecimal(22.3423D); 
    dest1 = numForm.format(bd1, dest1, pos); 
    System.out.println("dest1 = " + dest1); 
    System.out.println("INTEGER portion is at: " + pos.getBeginIndex() + 
     ", " + pos.getEndIndex()); 
    pos = new FieldPosition(NumberFormat.FRACTION_FIELD); 
    dest1 = numForm.format(bd1, dest1, pos); 
    System.out.println("FRACTION portion is at: " + pos.getBeginIndex() + 
      ", " + pos.getEndIndex()); 

出力

dest1 = 22.342 
INTEGER portion is at: 0, 2 
FRACTION portion is at: 9, 12 

のように使用することができます

// Create a pattern for our MessageFormat object to use. 
    String pattern = "he bought {0,number,#} " 
      + "apples for {1,number,currency} " + "on {2,date,MM/dd/yyyy}."; 
    String pattern2 = "I bought {0} " + "apples for {1} " + "on {2}."; 
    // Create values to populate the position in the pattern. 
    Object[] values = { 5, 7.53, new Date() }; 
    // Create a MessageFormat object and apply the pattern 
    // to it. 
    MessageFormat mFmt = new MessageFormat(pattern); 
    StringBuffer buf = new StringBuffer("Wow,"); 
    System.out.println(mFmt.format(values, buf, null)); 
+0

これは完全な投稿でしたか?あなたの最下位の例では、応答が途絶えたようです。この例では、mFmt.format(values、buf、null)の3番目の引数がnullではない場合がありますか?それはFieldPositionの引数なので、私の質問は何を求めています。 – john

+0

'FRACTION部分はat:9,12'ですか?あなたの例に従おうとしていましたが、「FRACTIONの部分は:3,6」などではありませんか? – ericpeters

関連する問題