How to format the output of resultSet via System.out.println in Java?

1

Hello, I am printing on the screen the result of a SELECT that I have stored in an object type resultSet (sql.ResultSet). But it comes out "all crooked". I tried to use the "\ t" between each printed column, but it did not help. Here is the part of the method that interests us:

public void selectCargos(String query){

            try {
                rs = st.executeQuery(query);
                System.out.printf("TABELA DE CARGOS\n\n");
                while (rs.next()){
                    System.out.println("ID: " +rs.getInt("id")+ "\t"+ "Nome do cargo: " +rs.getString("nome")+ "\t" + "Nível do cargo: " +rs.getString("nivel"));
    
asked by anonymous 30.01.2018 / 19:56

2 answers

1
 while ( rs.next() ) {
       System.out.println( " ID: " + rs.getInt("id") + "\n Nome do cargo: " + rs.getString("nome")  + "\n Nível do cargo: " + rs.getString("nivel") );
    }

You can print out form:

  System.out.println("##############################################"); 
  System.out.println(" ID: " + rs.getInt("id") );
  System.out.println(" Nome do cargo: " + rs.getString("nome") );
  System.out.println(" Nível do cargo: " + rs.getString("nivel") );
  System.out.println("##############################################");

or

You can override toString() if you have an object.

    public String toString() {
      return "ID: " + rs.getInt("id") + "\n Nome do cargo: " + rs.getString("nome") + "\n Nível do cargo: " + rs.getString("nivel");
    }
    
30.01.2018 / 20:30
1

You can use a type C format, using System.out.format:

String ID = "10"; //rs.getInt("id");
String nomeCargo = "Analista de Sistemas"; //rs.getString("nome");
String nivelCargo = "Senior"; //rs.getString("nivel");
System.out.format("ID: %-4s Nome do cargo: %-50s Nível do cargo: %s", ID , nomeCargo, nivelCargo);

The negative sign is to align left and the number is a fixed number of houses for your string (so it looks like a table). See the Ideone .

    
30.01.2018 / 20:23