如何使用 Java 中的 printf() 方法列印格式化文字?\n
printf() 方法可對輸出進行格式化,輸出到 java.io.PrintStream 或 java.io.PrintWriter。這些類還包含一個稱為 format() 的方法,可以產生相同的結果,因此我們在 printf() 方法中所瞭解到的任何內容都可以應用到 foramt() 方法中。
語法
System.out.printf(“format-string” [, arg1, arg2, … ]);
示例 1
import java.io.PrintStream;
public class PrintfTest1 {
public static void main(String[] args) {
int i = 1234;
System.out.printf("Decimal: %1$,d Octal: %1$o Hex: %1$x"\n, i);
String str = "Tutorials Point";
System.out.printf("%15s", str);
}
}輸出
Decimal: 1,234 Octal: 2322 Hex: 4d2 Tutorials Point
示例 2
public class PrintfTest2 {
public static void main(String[] args) {
String name = "Adithya";
int age= 30;
System.out.format("%-10s - %4d\n", name, age);
}
}輸出
Adithya - 30
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP