Pregunta

I want to print a Array in a specific order but i have no idea how, google is not helping me either.

Output:

[PR001, Slinger 6.20, 135, 380, PR002, Strip 1.07, 93, 470, PR003, Hal, 301, 965, PR004, Zolder, 23, 679]

Expected output:

PR001  Slinger 6.20   135   380 
PR002  Strip 1.07     93    470
PR003  Hal            301   965
PR004  Zolder         23    679

I get the ArrayList from a SQL query:

public ArrayList<String> selectAllePrinters() {
    ArrayList<String> printers = new ArrayList<>();
    try {
        Connection con = SimpleDataSource.getConnection();
        PreparedStatement stat = con.prepareStatement("SELECT * FROM printer;");
        ResultSet result = stat.executeQuery();
        while (result.next()) {
            printers.add(result.getString("printerid"));
            printers.add(result.getString("printernaam"));
            printers.add(result.getString("aantalkleur"));
            printers.add(result.getString("aantalZwart"));
        }
        result.close();
        stat.close();
        return printers;
    } catch (SQLException e) {
        System.out.println(e);
        return null;
    }
}

How can I do this? Thanks in advance!

¿Fue útil?

Solución

this is almost what you need :-) using tabs

List<String> l = new ArrayList<String>(Arrays.asList(ss)){;
    @Override
    public String toString(){
        Iterator<String> it = iterator();
        if (! it.hasNext())
            return "";

        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (;;) {
            i++;
            String e = it.next();
            sb.append(e);
            if (! it.hasNext())
                return sb.toString();
            sb.append('\t');
            if (i%4==0){
                sb.append("\n");
            }
        }
    }
};
System.out.println(l);

To have that perfect spacing between columns you want, you have to iterate over all elements twice to find the max width of each column.

But if tabs are OK for you (maybe you just want to copy and paste into a spreadsheet), you may try this way.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top