Java中MessageFormat.format方法中如何使用FieldPosition自变量?在网上看到的所有示例中,都没有使用FieldPosition参数。这个论点有什么用吗?我在这里查看规格:http://docs.oracle.com/javase/1.5.0/docs/api/java/text/MessageFormat.html。方法签名复制如下。

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

最佳答案

FieldPosition通过两个索引来跟踪格式化输出中字段的位置:两个字段的第一个字符的索引和一个字段的最后一个字符的索引。

你可以用像

  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


对于DateFormat

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


关于MessageFormat.format中使用的FieldPosition参数

// 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));

关于java - 如何在Java MessageFormat.format方法中使用FieldPosition参数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8919480/

10-10 07:53