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 好听的元旦简短祝福语