strings - Formatting Output

One of the long-awaited features that finally appeared in Java 5 is output formatting in the style of C’s printf() statement. Not only does this allow for simplified output code, but it also gives Java developers powerful control over output formatting and alignment.

  • printf()

uses pecial palceholders to show where the data should go.

  • System.out.format()

Java 5 instroduced the format() method, available to PrintStream or PrintWriter objects, which includes System.out. The format() method is modeled after C's printf(). Here's a example:

// strings/SimpleFormat.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public class SimpleFormat {
  public static void main(String[] args) {
    int x = 5;
    double y = 5.332542;
    // The old way:
    System.out.println("Row 1: [" + x + " " + y + "]");
    // The new way:
    System.out.format("Row 1: [%d %f]%n", x, y);
    // or
    System.out.printf("Row 1: [%d %f]%n", x, y);
  }
}
/* Output:
Row 1: [5 5.332542]
Row 1: [5 5.332542]
Row 1: [5 5.332542]
*/

format() and printf() are equivalent. The String class also has a static format() method which produces a formatted String (since 1.5).

They all call format(format, args) method.

  • The Formatter final Class

An interpreter for printf-style format strings. This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. Common Java types such asbyteBigDecimal, and Calendar are supported. Limited formatting customization for arbitrary user types is provided through the Formattable interface.

 

Formatters are not necessarily safe for multithreaded access. Thread safety is optional and is the responsibility of users of methods in this class.

// strings/Turtle.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.io.*;
import java.util.*;

public class Turtle {
  private String name;
  private Formatter f;

  public Turtle(String name, Formatter f) {
    this.name = name;
    this.f = f;
  }

  public void move(int x, int y) {
    f.format("%s The Turtle is at (%d,%d)%n", name, x, y);
  }

  public static void main(String[] args) {
    PrintStream outAlias = System.out;
    Turtle tommy = new Turtle("Tommy", new Formatter(System.out));
    Turtle terry = new Turtle("Terry", new Formatter(outAlias));
    tommy.move(0, 0);
    terry.move(4, 8);
    tommy.move(3, 4);
    terry.move(2, 5);
    tommy.move(3, 3);
    terry.move(3, 3);
  }
}
/* Output:
Tommy The Turtle is at (0,0)
Terry The Turtle is at (4,8)
Tommy The Turtle is at (3,4)
Terry The Turtle is at (2,5)
Tommy The Turtle is at (3,3)
Terry The Turtle is at (3,3)
*/
  • Format Specifiers

Here we'll use format specifiers to print a shopping receipt. This is a very simple example of the Builder design pattern, where you can create a starting object, add things to it, and finally complete it with the build() method:

// strings/ReceiptBuilder.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;

public class ReceiptBuilder {
  private double total = 0;
  private Formatter f = new Formatter(new StringBuilder());

  public ReceiptBuilder() {
    f.format("%-15s %5s %10s%n", "Item", "Qty", "Price");
    f.format("%-15s %5s %10s%n", "----", "---", "-----");
  }

  public void add(String name, int qty, double price) {
    f.format("%-15.15s %5d %10.2f%n", name, qty, price);
    total += price * qty;
  }

  public String build() {
    f.format("%-15s %5s %10.2f%n", "Tax", "", total * 0.06);
    f.format("%-15s %5s %10s%n", "", "", "-----");
    f.format("%-15s %5s %10.2f%n", "Total", "", total * 1.06);
    return f.toString();
  }

  public static void main(String[] args) {
    ReceiptBuilder receiptBuilder = new ReceiptBuilder();
    receiptBuilder.add("Jack's Magic Beans", 4, 4.25);
    receiptBuilder.add("Princess Peas", 3, 5.1);
    receiptBuilder.add("Three Bears Porridge", 1, 14.29);
    System.out.println(receiptBuilder.build());
  }
}
/* Output:
Item              Qty      Price
----              ---      -----
Jack's Magic Be     4       4.25
Princess Peas       3       5.10
Three Bears Por     1      14.29
Tax                         2.80
                           -----
Total                      49.39
*/

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/strings/SimpleFormat.java

3. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/io/PrintStream.java

4. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Formatter.java

5. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java

6. https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html

7. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/strings/ReceiptBuilder.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值