public class Divers {
public static void main(String args[]){
String format = \"|%1$-10s|%2$-10s|%3$-20s|\\n\";
System.out.format(format, \"FirstName\",
Here's an example of how I've handled centering column headers in Java:
public class Test {
public static void main(String[] args) {
String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };
// Find length of longest months value.
int maxLengthMonth = 0;
boolean firstValue = true;
for (String month : months) {
maxLengthMonth = (firstValue) ? month.length() : Math.max(maxLengthMonth, month.length());
firstValue = false;
}
// Display months in column header row
for (String month : months) {
StringBuilder columnHeader = new StringBuilder(month);
// Add space to front or back of columnHeader
boolean addAtEnd = true;
while (columnHeader.length() < maxLengthMonth) {
if (addAtEnd) {
columnHeader.append(" ");
addAtEnd = false;
} else {
columnHeader.insert(0, " ");
addAtEnd = true;
}
}
// Display column header with two extra leading spaces for each
// column
String format = " %" + Integer.toString(maxLengthMonth) + "s";
System.out.printf(format, columnHeader);
}
System.out.println();
// Display 10 rows of random numbers
for (int i = 0; i < 10; i++) {
for (String month : months) {
double randomValue = Math.random() * 999999;
String format = " %" + Integer.toString(maxLengthMonth) + ".2f";
System.out.printf(format, randomValue);
}
System.out.println();
}
}
}
public static String center(String text, int len){
String out = String.format("%"+len+"s%s%"+len+"s", "",text,"");
float mid = (out.length()/2);
float start = mid - (len/2);
float end = start + len;
return out.substring((int)start, (int)end);
}
public static void main(String[] args) throws Exception{
// Test
String s = "abcdefghijklmnopqrstuvwxyz";
for (int i = 1; i < 200;i++){
for (int j = 1; j < s.length();j++){
//center(s.substring(0, j),i);
System.out.println(center(s.substring(0, j),i));
}
}
}
Here's the answer using apache commons lang StringUtils.
Please note that you have to add the jar file to the build path. If you are using maven make sure to add commons lang in the dependencies.
import org.apache.commons.lang.StringUtils;
public class Divers {
public static void main(String args[]){
String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
System.out.format(format, "FirstName", "Init.", "LastName");
System.out.format(format,StringUtils.center("Real",10),StringUtils.center("",10),StringUtils.center("Gagnon",20);
System.out.format(String.format(format, (Object[])ex));
}
}