Search code examples
javastringformattingresultset

how to format output of resultSet correctly


I am having the following piece of code which should display resultSet nicely formatted in java. It however does not do what it is suppose to. I wonder why I am getting this strangely formatted output.

id        name         age     address      salary
1        Paul          32California                                   23000.0
2      Steeve          24New Jersy                                    22000.0
4      Andrew          24Washinghton                                  25000.0
3       Georg          29Colorado                                     21000.0
5        Andy          26Texas2                                       28000.0



public void  displayResultSet(ResultSet resultSet2) throws SQLException{
          ResultSetMetaData resultSetMetaData2 = resultSet2.getMetaData();
          int count2 = resultSetMetaData2.getColumnCount();
          Object[] objects = new Object[count2];

            for (int a = 1; a<=count2;a++){
                    System.out.printf("%1$12s", resultSetMetaData2.getColumnName(a));
            }
            System.out.println("");
            while (resultSet2.next()) {
                    for (int a = 1; a<=count2;a++){
                          Object o2 = resultSet2.getObject(a);
                          objects[a-1] =  o2.toString();
                         System.out.printf("%1$12s", o2.toString());
                        }
                    System.out.println("");
               }

        }

The insert quesries look like this:

INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul',32,'California',23000.00);
INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Steeve',24,'New Jersy',22000.00);
INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Georg',29,'Colorado',21000.00);
INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Andrew',26,'Washinghton',25000.00);
INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'Andy',26,'Texas2',28000.00);

Any help would be greatly appreciated.


Solution

  • In Java Formatter, width specifies the minimum number of characters to be written to the output. You should try to use precision as well if you want long text fields (like Address) to be truncated. Besides, you are relying on Object's toString() method to format non-text fields, so you'd probably want to trim those first:

    System.out.printf("%12.12s", o2.toString().trim());