Java : Formatting a string

I want to create a method which returns a string. However I want the string to be formatted as if the results were in a table. e.g.

Field one : content
The second field : content
F3: content

So basically I just need to work out, for each line, the appropriate space to insert inbetween the field name and the content data.

Any suggestions?

Thanks in advance guys

I’d say you’re best chance of getting a table appearance is to use tabs, represented by "\ " in Java.


String s = "Field" + "\	" + "value";

Of course field and value will be variables

You might also look at String.format() method:


System.out.println(String.format("%20s %20s %20s", "first field", "second field", "and another field"));
System.out.println(String.format("%20s %20s %20s", "more", "and more", "even more"));

This will output something like this:


         first field         second field    and another field
                more             and more            even more

See more here: http://java.sun.com/j2se/1.5.0/docs/api/index.html?java/util/Formatter.html

Thankyou both for the responses.

What does the %20s represent please?

Have you looked at the link I provided?

There you will find the syntax for formatting.

20 means the width of the field, “is a non-negative decimal integer indicating the minimum number of characters to be written to the output.”

So if you write there more than 20 chars it won’t be alilgned.

sorry, i looked but couldn’t work out how to justify the text. Don’t know how i missed it. Thankyou for your posts, very helpful, works perfect :slight_smile:

String s = String.format("%-20s %-20s", "Field one : ", "data");
String t = String.format("%-20s %-20s", "Second field : ", "more data");

return(s+"\
"+t);