從頭認識java-11.3 格式化輸出(1)
這一章節我們來討論一下格式化輸出,這個話題我們將通過兩個章節來展開描述。
在c語言體系裡面,用的最多的估計就是printf這個函數:
printf(%d%f,a,b)
上面簡單的一句,使用了格式化輸出,%d表示輸出整形數字,%f浮點數。
1.System.out.printf和System.out.format
java繼承c語言體系,當然也會有printf之類的函數,我們下面舉例:
package com.ray.ch11;public class Test {public static void main(String[] args) {int a = 1;String b = b;System.out.printf(%d%s, a, b);System.out.println();System.out.format(%d%s, a, b);}}
輸出:
1b
1b
在上面的代碼裡面System.out.printf和System.out.format是等價的。
2.Formatter類
package com.ray.ch11;import java.util.Formatter;public class Test {private Formatter formatter = new Formatter(System.out);// 這裡需要定義輸出的地方public void print(int a, String b) {formatter.format(%d%s, a, b);}public static void main(String[] args) {int a = 1;String b = b;new Test().print(a, b);}}
輸出:
1b
在使用Formatter類的時候需要注意,它需要定義輸出的地方,不然雖然字串的輸出已經存在記憶體,但是沒有輸出的地方。我們上面是輸出在控制台上面,因此把System.out放到裡面去。
總結:這一章節我們簡單講述了格式化輸出的兩個方面,一個是最簡單的printf函數,還有一個是Formmater類。