Java formatting text output

aceman817

Senior member
Jul 15, 2001
204
0
0
hey guys. is there a way to format text output in a table with java that is relatively simple? i know in C/C++ the 'setw' allows easy spacing of characters. i want to print a table of strings, integers, and double similar to the following:

Name Age GPA
------- ---- -----
Joe 20 3.6
Larry 17 3.4
Sue 19 3.7
 

Thyme

Platinum Member
Nov 30, 2000
2,330
0
0
You can write a function that will pad the String before you output it. Alternatively, you can use \t and see if that will keep it aligned.
 

aceman817

Senior member
Jul 15, 2001
204
0
0
thanks for the replies. i am using the new 5 jdk but the formatter class seems more suited to numbers. i can't seem to find a working example of how this would be done. it's sooo easy to handle basic formatting in c/c++ but java seems to make easy things difficult and difficult things easier.
 

Thyme

Platinum Member
Nov 30, 2000
2,330
0
0
Here's one:

final public String pad(final String target, final int count) {
StringBuffer buffer = new StringBuffer();
for (int current = 0; current < count; current++)
buffer.append(" ");
buffer.append(target);
return buffer.toString();
}

 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
The Formatter functionality is made handy in various printf methods in jdk5.0. Particularly in PrintWriter (which is what System.out and System.err are). I haven't used it but it should give you something pretty close to c's printf functions. Then you don't have to go importing 3rd party libraries.