| 方法 | 描述 |
|---|---|
| PrintStream printf(Locale l, String format, Object... args) PrintStream printf(String format, Object... args) | 列印格式化字串 |
舉例如下
class PrintfDemo {
public static void main(String[] args) {
String a = "Three are %d dogs and %d cats.\n";
String b = "Three are %f dogs and %f cats.\n";
String c = "Three are %s dogs and %s cats.\n";
System.out.printf(a, 33, 22);
System.out.printf(b, 11.0, 3.0);
System.out.printf(c, "54", "87");
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:PrintfDemo.java
功能:示範物件導向的基本觀念
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

其中 %d 、 %f 、 %s 等都是轉換字符,基本格式為百分比符號加上特定的英文字母, %d 表示整數 (integer) , %f 表示浮點數 (floating-point number) , %s 表示字串 (string) 。
具有轉換字符的字串稱為格字化字串,通常 printf() 的第一個參數為格字化字串,其後的參數須接格式化字串中對應型態的變數 (variable) 或字面常數 (literal) ,印出字串時轉換字符就會被變數或字面常數的值所取代。
常見轉換字符如下列表
| 轉換字符 | 說明 |
|---|---|
| 'b', 'B' | 真假值 |
| 'h', 'H' | 雜湊碼 |
| 's', 'S' | 字串 |
| 'c', 'C' | 字元 |
| 'd' | 十進位整數 |
| 'o' | 八進位整數 |
| 'x', 'X' | 十六進位整數 |
| 'e', 'E' | 科學記號浮點數 |
| 'f' | 十進位浮點數 |
| 'g', 'G' | 科學記號浮點數 |
| 'a', 'A' | 十六進位浮點數 |
| 't', 'T' | 日期時間 |
| '%' | 百分比符號 |
| 'n' | 換行符號 |
| 中英文術語對照 | |
|---|---|
| 類別 | class |
| 屬性 | field |
| 方法 | method |
| 整數 | integer |
| 浮點數 | floating-point number |
| 字串 | string |
| 變數 | variable |
| 字面常數 | literal |
參考資料
http://download.oracle.com/javase/6/docs/api/java/lang/System.html
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html
http://download.oracle.com/javase/6/docs/api/java/lang/System.html
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html
沒有留言:
張貼留言