我想在 Java 中创建自己的自定义函数,其工作方式与 C 中的 printf
完全相同。
喜欢
printf("My name is %c, my age is %d", "B", 23);
这将打印我的名字是B,我的年龄是23
或
printf("No of items %d", 2);
将打印No of items 2
。
最佳答案
Java中有多种这样的方法。
String.format(String, Object...)
Returns a formatted string using the specified format string and arguments.
和
System.out
可以使用PrintStream.printf(String, Object...)
和
Formatter
syntax适用于以上两者
例如,
String fmt = "i = %d%n";
int iv = 101;
System.out.print(String.format(fmt, iv));
System.out.printf(fmt, iv);
Formatter out = new Formatter(System.out);
out.format(fmt, iv);
out.flush();
输出
i = 101
i = 101
i = 101
tl;您的问题中的博士
使用“%s”表示String
和System.out.printf
,例如
System.out.printf("My name is %s,my age is %d%n", "B", 23);
System.out.printf("No of items %d%n", 2);
输出是(根据要求)
My name is B,my age is 23
No of items 2
关于java - Java 中的函数类似于 C 中的 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31645322/