Formatting Integers in a Line

Hi. Is there any way to write code to write out something like this in the Command Prompt?

|Name|Age |

| John|15|

With those two rows perfectly aligned? If so, how can I do this? Also, it'd be nice if for whatever name length that it be right-aligned.

Message was edited by:

ApRiX

Message was edited by:

ApRiX

[361 byte] By [ApRiXa] at [2007-11-27 5:45:00]
# 1
String.format() and the associated printf() methods (in Console, PrintStream and PrintWriter) allow you to do quite a lot of formatting using the format strings described in the Formatter class. You will have to write your own centering.
pbrockway2a at 2007-7-12 15:26:15 > top of Java-index,Java Essentials,Java Programming...
# 2

Got bored and wrote this:public class TableFormat {

public static void main(String[] args) {

System.out.printf("|%s|%s|%n", cen("Name", 11), cen("Age", 6));

System.out.printf("|%11s|%6d|%n", "John", 15);

System.out.printf("|%11s|%6d|%n", "Frederick", 101);

System.out.println("\nIt's common for strings to be left aligned...");

System.out.printf("|%-11s|%6d|%n", "John", 15);

System.out.printf("|%-11s|%6d|%n", "Frederick", 101);

System.out.println("\nWith floating point numbers there's the dot");

System.out.println("to keep aligned...");

System.out.printf("|%s|%s|%s|%n",

cen("Name", 11), cen("Age", 6), cen("Height", 8));

System.out.printf("|%-11s|%6d|%8.2f|%n", "John", 15, 1.8);

System.out.printf("|%-11s|%6d|%8.2f|%n", "Frederick", 101, 1.948);

}

static String cen(String str, int width) {

StringBuilder buf = new StringBuilder();

for(int i = 0; i < (width - str.length() + 1) / 2; i++) {

buf.append(' ');

}

buf.append(str);

for(int i = 0; i < (width - str.length()) / 2; i++) {

buf.append(' ');

}

return buf.toString();

}

}

The format strings are a bit cryptic to start with - but just follow the documentation and use the features you need. The effort can pay off because these strings are used more or less the same way in various languages. (The string literal "|%11s|%6d|%n" doesn't need to be written each time, it can be made a variable.)

pbrockway2a at 2007-7-12 15:26:15 > top of Java-index,Java Essentials,Java Programming...