原文:
The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out. Thus, you can use format or printf anywhere in your code where you have previously been using print or println. (解讀:之前熟悉的System.out是字元流物件,也就是說system.out是字元流物件的子類,所以作爲父類別字元流物件的方法printf and format都可以在System.out這個物件上呼叫)
// 之前的用法
System.out.println("hello");
System.out.print("sayhi");
// 補充的格式化輸出用法
System.out.format("", args);
System.out.printf("jiji");
這兩個java.io.PrintStream字元流的方法(format,printf)的語法相同:
public PrintStream format(String format, Object... args)
其中format是一個字串,用於指定要使用的格式,而args是使用該格式要列印的變數的列表。 一個簡單的例子是:
System.out.format("The value of " + "the float variable is " +
"%f, while the value of the " + "integer variable is %d, " +
"and the string is %s", floatVar, intVar, stringVar);
總結:printf 和format方法會用,瞭解即可。後面還有一個國際化的語言環境設定瞭解即可。
這個類可以自定義設定數位的格式,比較方便。瞭解介面,即查即用。