0
public class array1 {
    public static void main(String args[]) {
        int twod[][] = new int[4][5];
        int i, j, k = 0;
        for (i=0; i < 4; i++) {
            for (j=0; j < 5;j++) {
                twod[i][j] = k;
                k++;
            }  
        }

        for (i=0; i < 4; i++) {
            for (j=0; j < 5;j++) {
                System.out.println(twod[i][j] + " ");
            }
            System.out.println();
        }          
    }
}

Can any one tell me how to modify the code to get the output in matrix format? When I compile this program the output is 0 to 19 which is aligned vertically and not as in matrix format. Can any one help me?

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
jarvis
  • 29
  • 7

1 Answers1

3

Just use print() when you want to print a value, and only use println() when you actually want to print followed by a newline:

for (i=0; i < 4; i++) {
    for (j=0; j < 5; j++) {
        if (j > 0) System.out.print(" ");
        System.out.print(twod[i][j]);
    }
    // now that a complete row has been printed, go to the next line
    System.out.println();
}

Note that this answer might still leave you with a somewhat ratty-looking matrix, because not all numbers in your data set have the same width. We would need to do more work to get everything into nicely formatted columns.

Here is one improvement upon the above using String.format, with a fixed field width of 5:

for (i=0; i < 4; i++) {
    for (j=0; j < 5; j++) {
        if (j > 0) System.out.print(" ");
        System.out.print(String.format("%5s" , String.valueOf(twod[i][j])));
    }
    System.out.println();
}

This generates:

    0     1     2     3     4
    5     6     7     8     9
   10    11    12    13    14
   15    16    17    18    19
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360