CodeGym /课程 /JAVA 25 SELF /字符串格式化

字符串格式化

JAVA 25 SELF
第 9 级 , 课程 2
可用

1. 手动拼接的问题

当只需要输出一两个变量时,运算符 + 确实方便。但当数据较多时,拼接很快就会变得混乱,尤其是当需要数字格式化(例如保留 2 位小数)或换行时。

String name = "Oleg";
int age = 25;
double balance = 12345.67;

System.out.println("姓名: " + name + ", 年龄: " + age + ", 余额: " + balance + " 欧元。");

试图在拼接中“硬拧”格式化只会让可读性更差:

System.out.println("姓名: " + name + ", 年龄: " + age + ", 余额: " + String.format("%.2f", balance) + " 欧元。");

结论:简单拼接适合小场景,但构建复杂消息时应使用更强大的工具 — String.format()

2. String.format — 专业地格式化字符串

方法 String.format() 允许根据模板创建字符串,并把值按指定位置填入。

通用形式:

String result = String.format("模板", znacheniya);
  • %s — 字符串
  • %d — 整数
  • %f — 浮点数
  • %n — 换行(跨平台)
String name = "Oleg";
int age = 25;
double balance = 12345.6789;

String info = String.format("姓名: %s, 年龄: %d, 余额: %.2f 欧元。", name, age, balance);
System.out.println(info);
// 将输出: 姓名: Oleg, 年龄: 25, 余额: 12345.68 欧元。

String result = String.format("姓名: %s, 年龄: %d, 余额: %.2f 欧元", name, age, balance);
// %s — 字符串,%d — 整数,%.2f — 保留 2 位小数的浮点数

数字和字符串的格式化

固定小数位数的浮点数:

double price = 99.999;
System.out.println(String.format("价格: %.2f 欧元。", price)); // 价格: 100.00 欧元。

字段宽度与对齐:

int n = 7;
System.out.println(String.format("数字: [%5d]", n));   // 数字: [    7]
System.out.println(String.format("数字: [%-5d]", n));  // 数字: [7    ]

[5d] — 字段宽度 5,默认右对齐;
[-5d] — 字段宽度 5,左对齐。

字符串对齐:

String text = "Java";
System.out.println(String.format("[%10s]", text));  // [      Java]
System.out.println(String.format("[%-10s]", text)); // [Java      ]

百分号:

double percent = 0.125;
System.out.println(String.format("完成: %.1f%%", percent * 100)); // 完成: 12.5%

要输出百分号字符,请使用 %%

日期格式化(简要)

import java.util.Date;
Date now = new Date();
System.out.println(String.format("今天: %tD", now)); // 今天: 06/18/24
System.out.println(String.format("时间: %tT", now));   // 时间: 15:42:07

本地化与分隔符

默认使用系统的区域设置。若要指定自己的(例如使用逗号作为小数分隔符),请传入一个区域设置,例如 Locale.FRANCE

import java.util.Locale;
double price = 1234.56;
System.out.println(String.format(Locale.FRANCE, "%.2f", price)); // 1234,56

实践示例

示例 1:简短报告

String name = "Anna";
int tasks = 5;
double hours = 12.3456;

String report = String.format(
    "员工: %s%n完成的任务: %d%n耗时: %.1f",
    name, tasks, hours
);
System.out.println(report);

/* 输出:
员工: Anna
完成的任务: 5
耗时: 12.3
*/

示例 2:带对齐的表格

String header = String.format("%-10s | %5s | %8s", "姓名", "分数", "时间");
String row1 = String.format("%-10s | %5d | %8.2f", "Oleg", 95, 10.5);
String row2 = String.format("%-10s | %5d | %8.2f", "Anna", 100, 9.75);

System.out.println(header);
System.out.println(row1);
System.out.println(row2);

/* 输出:
姓名        |  分数 |     时间
Oleg       |    95 |    10.50
Anna       |   100 |     9.75
*/

示例 3:混合文本

int apples = 12;
int pears = 8;
System.out.println(String.format("我有 %d 个苹果和 %d 个梨。", apples, pears));

3. 实践:在我们的应用中格式化字符串

将格式化添加到控制台应用:余额始终保留两位小数,换行使用 %n

Scanner console = new Scanner(System.in);

System.out.print("请输入姓名: ");
String name = console.nextLine();

System.out.print("请输入年龄: ");
int age = console.nextInt();

System.out.print("请输入余额: ");
double balance = console.nextDouble();

// 格式化输出
String info = String.format("姓名: %s, 年龄: %d, 余额: %.2f 欧元。", name, age, balance);
System.out.println(info);

试一试:

  • 输入不同的值,并检查余额始终以两位小数输出(%.2f)。
  • 修改模板,使用 %n 添加换行。

4. 格式化字符串时的常见错误

错误 № 1:类型与占位符不匹配。
不能把字符串放进 %d,也不能把数字放进 %s

String.format("年龄: %d", "二十"); // 错误:期望数字,却传入了字符串

错误 № 2:把参数顺序弄错。
模板 %s %d,却先传了数字再传字符串——要么抛错,要么得到错误的输出。

错误 № 3:忽略区域设置。
期望用逗号作为小数分隔符,却看到的是点——请通过第一个参数将所需的区域设置显式传给 String.format(...)

错误 № 4:未转义的百分号。
要输出符号 %,请使用 %%,否则格式化会因错误而失败。

评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION