简体   繁体   English

JAVA函数,例如C的printf

[英]JAVA function like printf of C

I want to create my own custom function in java which work exactly same like the printf . 我想在Java中创建自己的自定义函数,其功能与printf完全相同。 Like 喜欢

printf("My name is %c ,my age is %d","B",23);

Which will return My name is B , My age is 23 . 这将返回我的名字是B,我的年龄是23。 or 要么

 printf("No of items %d",2);

which will return No of items 2. 它将返回项目编号2。

need help 需要帮忙

There are multiple such methods in Java. Java中有多种此类方法。

String.format(String, Object...)

Returns a formatted string using the specified format string and arguments. 使用指定的格式字符串和参数返回格式化的字符串。

and

System.out can use PrintStream.printf(String, Object...) System.out可以使用PrintStream.printf(String, Object...)

and

The Formatter syntax applies to both of the above Formatter语法适用于以上两种情况

For example, 例如,

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();

Outputs 产出

i = 101
i = 101
i = 101

tl;dr from your Question tl; dr来自您的问题

Use "%s" for a String and System.out.printf like 使用“%s”作为StringSystem.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);

Output is (as requested) 输出是(根据要求)

My name is B,my age is 23
No of items 2

You can go for System.out.printf(). 您可以使用System.out.printf()。 it acts same like as printf function in c. 它的作用与c中的printf函数相同。

you can code this way.. please share the feedback, as I tried some happy cases only. 您可以通过这种方式进行编码。.请分享反馈,因为我仅尝试了一些满意的案例。

public class Test1 {

 public static void main(String[] args) {
    printf("My name is %s ,my age is %d","B",23);
 }

 public static void printf(final String in, final Object... args) {
    System.out.println(String.format(in, args));
 }
}

Output : My name is B ,my age is 23 输出: My name is B ,my age is 23

We can use 我们可以用

System.out.print("My name is "+"B"+",my age is " +23);

or 要么

System.out.print("No of items "+2);
    String name = "B";
    int age = 23;
    System.out.printf("My name is %s, My age is %d", name,age);
    System.out.println();
    System.out.printf("No of items %d", 2);

Output: 输出:

My name is B, My age is 23
No of items 2

创建像function(String line,Object ... args)这样的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM