2

How do I format output by using printf.

suppose i want to print following in formatter.

testing testing testing testing
testingggg  testingggg  testingggg  testingggg

I am not asking about using "\t", I am asking on printf style formatting? If some one can give me suggestion and example. Or may be link with example. I can do it to fit my need.

2 Answers 2

10

I think you're looking for the Formatter class, which does printf-style formatting for Java.

For example, applied to your input:

    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb, Locale.US);

    formatter.format("%1$-15s %2$-15s %3$-15s %4$-15s\n", "testing", "testing", "testing", "testing");
    formatter.format("%1$-15s %2$-15s %3$-15s %4$-15s", "testingggg", "testingggg", "testingggg", "testingggg");

    System.out.println(sb.toString());

Produces:

testing         testing         testing         testing        
testingggg      testingggg      testingggg      testingggg    
0
0

You can use System.out.printf("%sggg" , t)

Where t = "testing" and ggg is just appended onto this string.

Hope this helps :D

1
  • no that was just example..i want to print them as if they are in table?
    – Milan
    Dec 22, 2011 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.