集册 Java实例教程 使用Formattable接口实现自定义格式化程序

使用Formattable接口实现自定义格式化程序

欢马劈雪     最近更新时间:2020-01-02 10:19:05

706
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用Formattable接口实现自定义格式化程序
/** 时代Java - N o w  J a v a . c o m 提 供 **/

import java.util.Formattable;

import java.util.FormattableFlags;

import java.util.Formatter;


public class Main {

  public static void main(String[] argv) {

    FormattablePerson fp = new FormattablePerson("Ken", "Smith");

    System.out.printf("%s %n", fp);

    System.out.printf("%#s %n", fp);

    System.out.printf("%S %n", fp);

    System.out.printf("%#S %n", fp);

  }

}


class FormattablePerson implements Formattable {

  private String firstName = "Unknown";

  private String lastName = "Unknown";
/* 来自 n o w  j a v a  . c o m*/

  public FormattablePerson(String firstName, String lastName) {

    this.firstName = firstName;

    this.lastName = lastName;

  }


  // Other code goes here...


  public void formatTo(Formatter formatter, int flags, int width, int precision) {

    String str = this.firstName + " " + this.lastName;


    int alternateFlagValue = FormattableFlags.ALTERNATE & flags;

    if (alternateFlagValue == FormattableFlags.ALTERNATE) {

      str = this.lastName + ", " + this.firstName;

    }


    // Check if uppercase variant of the conversio is being used

    
展开阅读全文