Java字符串format()方法示例。
Java提供了printf()和format()输出带有格式化数字的输出的方法。String类具有等效的类方法,format()该方法返回String对象而不是PrintStream对象。
使用String的静态format()方法使您可以创建可重复使用的格式化字符串,而不是一次性的打印语句。例如,代替-
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);你可以写-
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);示例
下面的示例通过在format()方法中使用特定的语言环境,格式和参数返回格式化的字符串值。
public class HelloWorld {
public static void main(String []args) {
String name = "Hello World";
String s1 = String.format("name %s", name);
String s2 = String.format("value %f",32.33434);
String s3 = String.format("value %32.12f",32.33434);
System.out.print(s1);
System.out.print("\n");
System.out.print(s2);
System.out.print("\n");
System.out.print(s3);
System.out.print("\n");
}
}输出结果
name Hello World value 32.334340 value 32.334340000000
热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话