如何在Java中使用printf()方法打印格式化的文本?
的printf()的方法允许我们格式输出到一个java.io.PrintStream中或java.io.PrintWriter中。这些类还包含一个称为format()的方法,该方法可以产生相同的结果,因此我们在此处为printf()方法阅读的内容也可以应用于format()方法。
语法
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 = "nhooo.com";
System.out.printf("%15s", str);
}
}输出结果
Decimal: 1,234 Octal: 2322 Hex: 4d2 nhooo.com
例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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿