如何在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 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短