格式化
-
输出 System.out.println(); System.out.print();
-
输出错误信息以红色输出 System.err.println(“hello world”);
-
格式化输出 System.out.printf();
转换符 | 说明 | 示例 |
---|---|---|
%s | 字符串类型 | “hello” |
%c | 字符类型 | ‘a’ |
%b | 布尔类型 | true |
%d | 整数类型(十进制) | 10 |
%f | 浮点类型 | 10.00 |
%n | 换行符 | |
%tx | 日期与时间类型(x代表不同的日期与时间转换符) | |
…… | …… | …… |
格式化整数
//0
//在数字前面补0
String.format("|%04d|", 10); // 输出:|0010|
// +
//为正数或者负数添加符号
String.format("%+d",10); //输出 +10
//空格
//在整数之前添加指定数量的空格
String.format("%4d",99); //输出| 99|
字符和字符串转换
public class StringFormatTest {
public static void main(String[] args) {
// %s %d
String name = "张三";
int age = 8;
char score='A';
System.out.printf("姓名:%s,年龄:%02d岁,成绩:%c", name, age,score);
//%n 换行符
System.out.printf("%n hello %n\n java \n");
}
}
运行结果:

日期格式化
import java.util.Date;
public class DateFormatTest {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);//未格式化的时间
System.out.printf("%tF %n",d);//使用 “%tY-%tm-%td“ 格式的 ISO 8601 日期。
System.out.printf("%tR %n",d);//24小时制的时间,如:“%tH:%tM“。
System.out.printf("%tT %n",d);//24小时制的时分秒,如: “%tH:%tM:%tS“。
System.out.printf("%1$tY年%1$tm月%1$td日 %1$tT %1$tA",d); //2021年07月29日 14:41:38 星期四
}
}
运行结果:
