Java基礎學習(四)

字符串部分的補充

格式化輸出

System.out.format()

format()方法和printf()方法是等價的。

Formatter類

可以將Formatter類看做是一個翻譯器,它能把你的格式化字符串和數據翻譯成你需要的結果。

import java.util.*;
import java.io.*;
public class TestForJava {
    private String name;
    private Formatter f;
    public TestForJava(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[] atgs){
        PrintStream outAlias=System.out;

        TestForJava tommy=new TestForJava("Tommy",new Formatter(System.out));
        TestForJava terry=new TestForJava("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);
    }
}
運行結果:
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)

上例代碼中,所有的tommy都將輸出到System.out中,而所有的terry都將輸出到outAlias(System.out的一個別名)中。

Formatter類的構造器經過重載可以接受多種輸出目的地,最常用的是PrintStream(),OutputStream()和File中。

發佈了21 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章