如何在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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短