java如何引用format
在Java中使用String.format方法
Java中可以通过String.format方法进行字符串格式化。该方法使用类似于C语言中printf的格式化语法,允许将各种数据类型格式化为指定模式的字符串。
基本语法格式:

String formattedString = String.format(formatString, arguments...);
常用格式化符号
%s:字符串%d:十进制整数%f:浮点数%t:日期/时间%b:布尔值%n:换行符
数字格式化示例
double num = 123.45678;
String result = String.format("浮点数: %.2f", num); // 保留两位小数
// 输出: "浮点数: 123.46"
日期时间格式化
Date now = new Date();
String dateStr = String.format("当前时间: %tY-%tm-%td", now, now, now);
// 输出类似: "当前时间: 2023-05-15"
参数索引控制
可以使用n$指定参数位置:
String str = String.format("%2$s %1$s", "World", "Hello");
// 输出: "Hello World"
格式化输出到控制台
也可以直接使用System.out.printf方法:

System.out.printf("姓名: %s, 年龄: %d%n", "张三", 25);
格式化字符串重用
创建格式化模板重复使用:
String template = "用户ID: %d, 用户名: %s";
String user1 = String.format(template, 1001, "Alice");
String user2 = String.format(template, 1002, "Bob");
格式化标志字符
可以添加标志字符控制输出:
-:左对齐+:显示正负号0:数字前补零,:使用千位分隔符
String str = String.format("%+,10d", 12345);
// 输出: " +12,345"






