![如何使用Java中的printf()方法打印格式化文本?](https://img.php.cn/upload/article/000/887/227/169529382765782.jpg)
printf() 方法允许我们将输出格式化到 java.io.PrintStream 或 java.io.PrintWriter。这些类还包含一个名为 format() 的方法,它可以产生相同的结果,所以无论我们在这里读到的是关于 printf() 方法的内容,都可以应用于 format() 方法。
语法
1 | System.out.printf(“format-string” [, arg1, arg2, … ]);
|
登录后复制
示例1
1 2 3 4 5 6 7 8 9 | 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);
}
}
|
登录后复制
输出
1 2 | Decimal: 1,234 Octal: 2322 Hex: 4d2
Tutorials Point
|
登录后复制
示例2
1 2 3 4 5 6 7 | public class PrintfTest2 {
public static void main(String[] args) {
String name = "Adithya" ;
int age= 30;
System.out.format( "%-10s - %4d\n" , name, age);
}
}
|
登录后复制
输出
以上是如何使用Java中的printf()方法打印格式化文本?的详细内容。更多信息请关注PHP中文网其他相关文章!