Pergunta

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.

Foi útil?

Solução

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    

Outras dicas

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

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

Hope this helps :D

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top