-1
import java.io.PrintStream;

public class JavaApplication16 {

    public static void main(String[] args) {
        // Create 2-dimensional array.
        String[][] values = new String[12][4];
        String format;
        format = "|%1$-30s|%2$-10s|%3$-20s|\n";

        // Assign three elements in it.
        values[0][0] = "Mnd";
        values[0][1] = "Stroom";
        values[0][2] = "Water";
        values[0][3] = "Telefoon";
        values[1][0] = "Jan";
        values[1][1] = "1000";
        values[1][2] = "1500";
        values[2][0] = "Feb";
        values[3][0] = "Mrt";

        values[3][2] = "3";

        // Loop over top-level arrays.
        for (String[] sub : values) {
            // Loop and display sub-arrays.
            for (String sub1 : sub) {
                PrintStream printf;
                printf = System.out.printf(sub1 + " ");
            }
            System.out.println();
        }
    }
}

Output is:

Mnd Stroom Water Telefoon
Jan 1000 1500 null
Feb null null null
Mrt null 3 null
null null null null
null null null null
null null null null
null null null null
null null null null
null null null null
null null null null
null null null null
Prasanna Kumar H A
  • 2,923
  • 4
  • 20
  • 46
RayJay
  • 1
  • 1

1 Answers1

1

I don't quite understand your format variable as it is unused. If you want to have fixed column sizes, you can do this with that kind of formatting, see this answer: How can I pad a String in Java?

If you want flexible size of columns, depending on the elements in the table, here is the pseudo code:

  1. Create a single dimensional array of integers with length equal to the number of columns. Populate it with the length of the longest String in that column. In your case it should be int[] columnSize = {4, 6, 5, 8};.
  2. When printing an item item from column x, add trailing spaces equal to columnSize[x] - item.toString().length() + 1.
  3. You can skip printing the trailing spaces for x == columnSize.length.
Community
  • 1
  • 1
Jaroslaw Pawlak
  • 5,270
  • 7
  • 26
  • 52