從頭認識java-11.3 格式化輸出(1)

來源:互聯網
上載者:User

從頭認識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類。

 

 


 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.