格式化字符串的三种方法:System.out.printf() 方法:使用占位符和格式说明符格式化字符串。Formatter 类:创建 Formatter 对象并调用 format() 方法格式化字符串。String.format() 方法:静态方法,直接格式化字符串。

<code class="java">// 使用占位符和格式说明符进行格式化
String name = "John Doe";
int age = 30;
float height = 1.8f;
System.out.printf("Name: %s, Age: %d, Height: %.2f", name, age, height);
// 使用 Formatter 类进行格式化
Formatter formatter = new Formatter();
formatter.format("Name: %s, Age: %d, Height: %.2f", name, age, height);
String formattedString = formatter.toString();
System.out.println(formattedString);
// 使用 String.format() 方法进行格式化
String formattedString2 = String.format("Name: %s, Age: %d, Height: %.2f", name, age, height);
System.out.println(formattedString2);</code>