/*
* 2018年3月30日15:28:34
* 代码目的:
* 演示Java中通过Formatter类进行字符串格式化的过程。
* Formatter的构造器经过重载可以接受多种输出目的地,最常用的还是控制台
* public static final PrintStream out = null; out为System类中定义的static final
*
* */
//: strings/Turtle.java
import java.io.*;
import java.util.*;
public class Turtle {
private String name;
//私有成员Formater类对象,用它进行格式化
private Formatter f;
public Turtle(String name, Formatter f) {
this.name = name;
this.f = f;
}
public void move(int x, int y) {
//格式化,也可以通过调用System.out.printf()或者
//System.out.format()完成相同的功能。
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)
*///:~