简体   繁体   中英

JAVA function like printf of C

I want to create my own custom function in java which work exactly same like the printf . Like

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

Which will return My name is B , My age is 23 . or

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

which will return No of items 2.

need help

There are multiple such methods in 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...)

and

The Formatter syntax applies to both of the above

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

Use "%s" for a String and System.out.printf like

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(). it acts same like as printf function in c.

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

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)这样的函数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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